Socket Code

Hey guys,
I am having trouble with the following task listed below. The problem is I am not sure how to write a while loop that reads text from the server socket input stream, line by line, and prints it out to the web page, using out.println(...);
Also how do I call the toHTMLString() method?
          DCACHANGE4 - add a while loop that reads text from the
          server socket input stream, line by line, and prints
          it out to the web page, using out.println(...);
          Note that because the reply from the server will contain
          XML, you will need to call upon the toHTMLString() method
          defined below to escape the < and > symbols so that they
          will display correctly in the web browser.
          Also note that as you receive the reply back from the
          server, you should look out for the special <!--QUIT-->
          string that will indicate when there is no more data
          to receive.
// Close all the streams we have open, and then close the socket
sockOut.close();
sockIn.close();
mySocket.close();
%>
<%!
This method will escape any special HTML characters in a string
of text. For example, if you are trying to print out an XML
document using a JSP, you need to escape all the '<' and '>' tags
so that the web browser will not try and treat them as HTML.
Note that generic utility code like this would usually be put into
a JavaBean, but is put in the JSP here for simplicity.
This code taken from H. Bergsten, JavaServer Pages, O'Reilly, 2001.
private static String toHTMLString(String in) {
StringBuffer out = new StringBuffer();
for (int i = 0; in != null && i < in.length(); i++) {
char c = in.charAt(i);
if (c == '\'') {
out.append("&#39;");
else if (c == '\"') {
out.append("&#34;");
else if (c == '<') {
out.append("<");
else if (c == '>') {
out.append(">");
else if (c == '&') {
out.append("&");
else {
out.append(c);
return out.toString();
%>
</pre>
<hr />

ok i'm close to solving the problem but not quiet.
i've added the following code to my server:
     while ((inputLine = in.readLine()) != null) {
                  outputLine = inputLine;
                  out.println(outputLine);
                    System.out.println(outputLine);
             }it appears to be recieving the xml document that is sent to it thats generating from the textfields:
Server started at port 10162
<?xml version="1.0" encoding="UTF-8"?>
<cd>
    <title>Adams2</title>
    <artist>Bryan</artist>
    <tracklist>
        <track id="1">
            <title>Halo</title>
            <time>skj</time>
            <rating>1</rating>
        </track>
    </tracklist>
</cd>
<!--QUIT-->... however it think the problem lays in cdprocess.jsp
whenever i use sockIn.readLine()
it just stalls even without any while loops!
i've tried out.println("hello"); theres no problem with printing something out.
Another problem i found strange was when i aborted the connected to the server (i.e. terminated it) it generated the results but only one of them for some weird reason (rating)

Similar Messages

  • EXC_BAD_ACCESS and seg faults with BSD Sockets code

    Hi,
    I've been having some problems with sockets programming on a new MacBook that I've decided to do some programming on.
    So, I wrote a pretty simple program to test if the sockets are working properly, and it's only partially working.
    I've been compiling via gcc on the command line, but then I tried Xcode to see if that made any difference, and it didn't.
    Also, this program works flawlessly on FreeBSD 6.2. The Apple Developer website says that BSD sockets should work perfectly.
    Here's the code: http://www.wraithnj.com/matt/Programming/C/scrabble/server/server.c
    I've been testing this code with netcat, telnet, and this too: http://www.wraithnj.com/matt/Programming/C/scrabble/client/client.c
    Xcode and GDB reveals that it fails line 57. Or at least that's where the break point is set. Appearantly it doesn't like the FD_SET() macro... Perhaps I'm just being an idiot and don't know how to use Xcode.
    So, this is what it looks like when it fails (after connecting with a client):
    matt@mdwosx1:~/Programming/C/scrabble/server# ./server2
    Connection from: 127.0.0.1 Socket: 4
    Then the program doesn't crash. It sends the "playerid." The client receives the 1 sent.
    Then if I try to send the server any information (typing in stuff from the client) the server doesn't show that it has received the information. Then if I send 'q' from the client. It has a segmentation fault. If I just do Ctrl+C with the client, it receives another segmentation fault. I don't understand what memory it's trying to write to that it can't. I'm assuming that it's having trouble writing to the fd_set master because that's where gdb leads me, but that's confusing because that works fine on FreeBSD.
    If I connect two clients, the second the second client connects it runs into an infinite loop.
    It repeats this:
    DATA From: 2.0.0.0 Socket: 3 Data:
    DATA From: 2.0.0.0 Socket: 3 Data:
    DATA From: 2.0.0.0 Socket: 3 Data:
    DATA From: 2.0.0.0 Socket: 3 Data:
    DATA From: 2.0.0.0 Socket: 3 Data:
    DATA From: 2.0.0.0 Socket: 3 Data:
    Until you quit from both clients, where it drops a segmentation fault.
    The GDB in Xcode says EXCBADACCESS.
    I honestly have no clue what I'm doing wrong. I added a whole bunch of header files (in case Mac OS X depends upon something else). I recompiled it every which way. I reconfigured Xcode every which way.
    Could anybody help me or shed some light on what I'm doing wrong?
    -WraithM

    I did have an extra byte on each of my character arrays. The fix was adding two extra bytes. For example, with my playerid in the client, originally (in the program before the fix that worked perfectly on FreeBSD) I had playerid[1] in the declaration. Aka, two bytes. I store the first byte in the first element, then I stored the null in the second element. Under OS X, when I declared 2 elements, the recv function was overflowing into the next variable (so, it was taking up three elements, somehow). So, then I redeclared my playerid array with three elements, and it worked out. So, there's a specific difference between OS X and FreeBSD. I also did specifically take in one less byte than size of my array and null terminated by myself. For example,
    numbytes = recv(sock, playerid, 1, 0);
    playerid[numbytes] = '\0';
    Note that I originally had it declared as 2 bytes long. So, I read 1 byte in, then I null terminate the second byte. numbytes should be 1 if I'm reading 1 byte. That's what recv sends as the return value. Therefore playerid[1] = '\0';
    I did EXACTLY what you suggested even before I fixed it. Okay, so your suggestion of what the problem is isn't a fair assessment of the situation. There's a specific difference between OS X and FreeBSD. Remember, this code worked perfectly on FreeBSD before and after the changes. So, when I null terminate, it's taking up two bytes somehow. Also, it's not like the null termination is being put in the third element of the array because I tried doing:
    playerid[numbytes - 1] = '\0'; It over wrote the first element.
    I don't need to review C strings. I'm getting lucky because I guessed how to fix the situation based upon the perceived differences between OS X and FreeBSD, not because I'm making random changes. I need somebody to explain what OS X is doing that FreeBSD isn't doing (or visa versa).
    Also, you're wrong:
    Your code only works because you make sure that atoi() is less than 2 and you've make that playerfd array have [two elements].
    I originally declared it with TWO elements, and it didn't work because I didn't offset the index of playerfd. Then I declared it with three elements, and it worked. That's because I changed the size of playerfd, but now I fixed the problem (and now I am back to having two elements with a new solution), but that doesn't explain why this worked on FreeBSD and not OS X.
    Addmittedly, I didn't think about this before, but here's the real way I should have done this.
    if(atoi(&playerid) < 2)
          playerfd[atoi(&playerid) - 1] = newsock;
    Because the playerid is either 1 or 2, it'd put it in either the second or third element, not the first or second element. So, I just offset the atoi, and now I can do that with a two element declaration. It was a silly mistake on my part.
    However, that doesn't explain what's going on in the client where the null-termination is going over into the next array (unless I have 3 elements instead of something that should have 2 elements (the number then the null termination)). Nor does that explain why this code worked on FreeBSD. I can understand why the server worked in FreeBSD. There could have been nothing important after the playerfd array in the server (which doesn't really make sense, because the compilers should have the same variables next to eachother, but conceivably that's how it'd work). However, on the client, if I tried to do printf of playerid with a strange offset like in the server, then I'd get this:
    0x[0031]00 (the brackets defining where the playerid array with 2 elements is)
    It wouldn't print anything because it'd hit the null right off the bat.
    So, what must be happening is this:
    0x[3100]00
    The 00 after the playerid bracket is where the overflow is occurring. Normally, the socket file descriptor is there, and that gets overwritten with 0. In FreeBSD, it worked fine.
    So, when I define the array to be 3 elements long, it must be working like this:
    0x[310000]04 (04 being the socket file descriptor that occurs after the playerid array)
    There are two nulls... Something is strange about this. This is what I don't understand as not working in OS X and working in FreeBSD.
    Could anybody explain this?
    P.S. I don't like initializing all of my data, nor error checking during designing of a basic program. I put them in afterwards because I find them to be aesthetically displeasing, and it makes it more difficult to find stuff. I know it's stupid, but that's how I work. I put in error checking when I'm debugging specific sections, and then put it in everywhere after is all worked out. My coding style is not the problem. Admittedly, I was stupid with the server, but I honestly don't understand the client. The nature of the server and client are different. In the server, I'm using an integer array, and in the client I'm using a character array.
    Message was edited by: WraithM

  • Issue porting WebLogic 8.1 SSL Socket code to WebLogic 9.2

    I did not write this code, but am trying to port the code from Weblogic 8.1 to Weblogic 9.2. The code comes from a custom OpenLDAPAuthenticator, that uses a SSL Socket to connect to an LDAP server.
    The following lines are used:
    Socket socket = SSLSocketFactory.getDefaultJSSE().createSocket(host, port);
    if (socket instanceof SSLSocket) {
      SSLContextWrapper sslcontextwrapper = SSLContextManager.getInstance().getDefaultSSLContext();
      sslcontextwrapper.forceHandshakeOnAcceptedSocket((SSLSocket) socket);
    }Does anyone know what this forceHandshakeOnAcceptedSocket method does, and if there is way to write this in WebLogic 9.2?
    Thanks

    I did not write this code, but am trying to port the code from Weblogic 8.1 to Weblogic 9.2. The code comes from a custom OpenLDAPAuthenticator, that uses a SSL Socket to connect to an LDAP server.
    The following lines are used:
    Socket socket = SSLSocketFactory.getDefaultJSSE().createSocket(host, port);
    if (socket instanceof SSLSocket) {
      SSLContextWrapper sslcontextwrapper = SSLContextManager.getInstance().getDefaultSSLContext();
      sslcontextwrapper.forceHandshakeOnAcceptedSocket((SSLSocket) socket);
    }Does anyone know what this forceHandshakeOnAcceptedSocket method does, and if there is way to write this in WebLogic 9.2?
    Thanks

  • Applect socket code reconnecting after I close it, but how

    Hi people. I�m making a client / server socket program and Im also using a lot of DHTML and JavaScript.
    Here is my problem:
    I use applets that you cant see because all their purpose is is to communicate with teh server using sockets. When I want to close the connection I want to applet to die and be removed from the body of the DOM object in the browser. The applets sit in <div>'s. When I close the connection to the server and remove the div that the applet is sittin on, in FF its ok, but in IE, the applet code stops, disconnects, but then reconnects. Anyone know what thr problem is.
    Thanks

    Do you have Logitech Gaming software installed?  If so, go to the software to disable Media Applet plug in.

  • Can we use MS C++ Socket code to send to a labview socket vi?

    See above.

    No, the VIs you are referring to in LabVIEW use National Instruments DataSocket technology. This is not the same as Windows Sockets communication that you are referring to from Visual C++. They are not compatible to be used together. We do provide libraries for Visual C++ for DataSocket that come with our Measurment Studio package. Measurement Studio includes classes like CNiDataSocket that can be used to communicate with the LabVIEW DataSocket VIs.
    Best Regards,
    Chris Matthews
    National Instruments

  • Socket source code

    I created a pingpong program that sends increasing sized packets back and forth between two computers to test the bandwidth. I'm getting very unusual results. See the graph at http://www.activeclickweb.com/pingpong.jpg
    Is there any way to get at the native socket code to see what is happening? Or has anyone else seen this and can explain it?
    Thanks
    Brian

    Hi Brian,
    It sounds like this might be a better question for the Java Networking Forum:
    http://forum.java.sun.com/forum.jspa?forumID=536
    I would suggest reposting your question there.
    -Larry

  • Writing to socket with setinterval not working in windows

    Hello Everyone,
    I'm trying to stream a big file to my server, and was using 'setInterval' just fine to slowly upload it from OS X, but when I moved my AIR application to a Windows Vista computer, it no longer worked. I started doing some investigation and found out that 'socket.writeBytes' function was not working inside of 'setInterval'. I then moved the code inside of 'setInterval' to outside of it and everythink worked, but obviously it was no longer streaming. Thinking there was something wrong with 'setInterval', I tried it  without the 'socket.writeBytes' function in it, and it started working fine.
    Not sure what is happening, but it seems like a bug in the air.Socket code.
    Here is my code:
        var socket = new air.Socket();
        socket.addEventListener(air.Event.CONNECT, function(e) {
            var stream = setInterval(function() {
                   socket.writeBytes(filePart, 0, filePart.length);
                    if (isDone) {
                        clearInterval(stream);
            }, 1000);
        socket.connect("myServer", 80);
    P.S. I also tried using 'air.Timer' and it was the same behavior as 'setInterval'.
    Thanks for any help.

    Hi,
    You should use the flush method:
    http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/Socket.html#f lush%28%29
    "Flushes any accumulated data in the socket's output buffer.
    On some operating systems, flush() is called automatically between execution frames, but on other operating systems, such as Windows, the data is never sent unless you call flush() explicitly. To ensure your application behaves reliably across all operating systems, it is a good practice to call the flush() method after writing each message (or related group of data) to the socket."
    I hope this helps!
    -Erica

  • Establishing a socket connection between a .swf file and a socket-test program (TCP/IP builder - Windows), in AS3.

    I have an issue with a college project I'm working on.
    Using Actionscript 3, I made a simple .swf program, an animated, interactive smiley, that 'reacts' to number inputs in a input-box.
    For the sake of the project, I now need to make the framework for establishing a socket connection with the smiley .swf, and another program.
    This is where I encounter issues. I have very little knowledge of AS3 programming, so I'm not certain how to establish the connection - what's required code-wise for it, that is.
    To test the connection, I'm attempting to use the "TCP/IP builder" program from windows, which lets me set up a server socket. I need to program the .swf file into a client - to recognize it, connect to it, then be able to receive data (so that the data can then be used to have the smiley 'react' to it - like how it does now with the input-box, only 'automatically' as it gets the data rather than by manual input).
    My attempts at coding it are as follows, using a tutorial (linked HERE):
    //SOCKET STUFF GOES HERE
        var socket:XMLSocket;        
        stage.addEventListener(MouseEvent.CLICK, doConnect); 
    // This one connects to local, port 9001, and applies event listeners
        function doConnect(evt:MouseEvent):void 
        stage.removeEventListener(MouseEvent.CLICK, doConnect); 
        socket = new XMLSocket("127.0.0.1", 9001);   
        socket.addEventListener(Event.CONNECT, onConnect); 
        socket.addEventListener(IOErrorEvent.IO_ERROR, onError); 
    // This traces the connection (lets us see it happened, or failed)
        function onConnect(evt:Event):void 
            trace("Connected"); 
            socket.removeEventListener(Event.CONNECT, onConnect); 
            socket.removeEventListener(IOErrorEvent.IO_ERROR, onError); 
            socket.addEventListener(DataEvent.DATA, onDataReceived); 
            socket.addEventListener(Event.CLOSE, onSocketClose);             
            stage.addEventListener(KeyboardEvent.KEY_UP, keyUp); 
        function onError(evt:IOErrorEvent):void 
            trace("Connect failed"); 
            socket.removeEventListener(Event.CONNECT, onConnect); 
            socket.removeEventListener(IOErrorEvent.IO_ERROR, onError); 
            stage.addEventListener(MouseEvent.CLICK, doConnect); 
    // Here, the flash tracks what keyboard button is pressed.
    // If 'q' is pressed, the connection ends.
            function keyUp(evt:KeyboardEvent):void 
            if (evt.keyCode == 81) // the key code for q is 81 
                socket.send("exit"); 
            else 
                socket.send(evt.keyCode); 
    // This one should handle the data we get from the server.
            function onDataReceived(evt:DataEvent):void 
            try { 
                trace("From Server:",  evt.data ); 
            catch (e:Error) { 
                trace('error'); 
        function onSocketClose(evt:Event):void 
            trace("Connection Closed"); 
            stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp); 
            socket.removeEventListener(Event.CLOSE, onSocketClose); 
            socket.removeEventListener(DataEvent.DATA, onDataReceived);
    Trying to connect to the socket gives me either no result (other than a 'connection failed' message when I click the .swf), or the following error:
    Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: file:///C|/Users/Marko/Desktop/Završni/Flash%20documents/Smiley%5FTCP%5FIP%5Fv4.swf cannot load data from 127.0.0.1:9001.
        at Smiley_TCP_IP_v4_fla::MainTimeline/doConnect()[Smiley_TCP_IP_v4_fla.MainTimeline::frame1:12] 

    Tried adding that particular integer code, ended up with either errors ("use of unspecified variable" and "implicit coercion") , or no effect whatsoever (despite tracing it).
    Noticed as well that the earlier socket code had the following for byte reading:
    "sock.bytesAvailable > 0" (reads any positive number)
    ...rather than your new:
    "sock.bytesAvailable != 0" (reads any negative/positive number)
    Any difference as far as stability/avoiding bugs goes?
    So then, I tried something different: Have the program turn the "msg" string variable, into a "sentnumber" number variable. This seemed to work nicely, tracing a NaN for text (expected), or tracing the number of an actual number.
    I also did a few alterations to the input box - it now no longer needs the 'enter' key to do the calculation, it updates the animation after any key release.
    With all this considered and the requirements of the project, I now have a few goals I want to achieve for the client, in the following order of priority:
    1) Have the "sentnumber" number variable be recognized by the inputbox layer, so that it puts it into the input box. So in effect, it goes: Connect -> Send data that is number (NaN's ignored) -> number put into input box -> key press on client makes animation react. I optionally might need a way to limit the number of digits that the animation reacts to (right now it uses 1-3 digit numbers, so if I get sent a huge number, it might cause issues).
    - If the NaN can't be ignored (breaks the math/calculus code or some other crash), I need some way of 'restricting' the data it reads to not include NaN's that might be sent.
    - Or for simplicity, should I just detect the traced "NaN" output, reacting by setting the number variable to be "0" in such cases?
    2) After achieving 1), I'll need to have the process be automatic - not requiring a keyboard presses from the client, but happening instantly once the data is sent during a working connection.
    - Can this be done by copying the huge amounts of math/calculus code from the inputbox layer, into the socket layer, right under where I create the "sentnumber" variable, and modifying it delicately?
    3) The connection still has some usability and user issues - since the connection happens only once, on frame 1, it only connects if I already have a listening server when I run the client, and client can't re-connect if the server socket doesn't restart itself.
    I believe to do this, I need to make the connection happen on demand, rather than once at the start.
    For the project's requirement, I also need to allow client users to define the IP / port it's going to connect to (since the only alternative so far is editing the client in flash pro).
    In other words, I need to make a "Connect" button and two textboxes (for IP and port, respectively), which do the following:
    - On pressing "Connect", the button sets whatever is in the text boxes as the address of the IP and port the socket will connect to, then connects to that address without issues (or with a error message if it can't due to wrong IP/port).
    - The connection needs to work for non-local addresses. Not sure if it can yet.
    - On re-pressing connect, the previous socket is closed, then creates a new socket (with new IP/port, if that was altered)
    It seems like making the button should be as simple as putting the existing socket code under the function of a button, but it also seems like it's going to cause issues similar to the 'looping frames' error.
    4) Optional addition: Have a scrolling textbox like the AIR server has, to track what the connection is doing on-the-fly.
    The end result would be a client that allows user to input IP/Port, connects on button press (optionally tracking/display what the socket is doing via scrollbox), automatically alters the smiley based on what numbers are sent whilst the connection lasts, and on subsequent button presses, makes a new connection after closing off the previous one.
    Dropbox link to new client version:
    https://www.dropbox.com/s/ybaa8zi4i6d7u6a/Smiley_TCP_IP_v7.fla?dl=0
    So, starting from 1), can I, and how can I, get the number variable recognized by "inputbox" layer's code? It keeps giving me 'unrecognized variable' errors.

  • JNI crash sockets

    I am trying to write a Java library around a piece of hardware that currently does not support Java. As the first part of the task, I need to establish a TCP/IP connection between a client and server. I wrote some test code in C that is very simple socket code that can be found on tons of example sites (yes I know Java has built in classes for this, but the connection must exist in the native side).
    I wrapped everything into a simple ConnectToServer and ConnectToClient functions (everything is hardcoded, so no parameters are passed) in a .so and can establish and run the connection without a hitch in a C++ program that loads the .so. When I load the .so and try to call the functions in a Java harness, the JVM crashes with a SIGSEGV in the server side during the accept call (the client does establish the connection, so it must be crashing somewhere pretty far into the accept( ) call). I have verified this crash by building and running the debug version of hotspot in gdb.
    Im running Red Hat Enterprise Linux Server release 6.1 (Santiago) and Java VM: Java HotSpot(TM) 64-Bit Server VM (21.0-b17 mixed mode linux-amd64 compressed oops).
    Am I not allowed to call native library functions that have system calls in them during JNI, or am I missing something else that is not immediately obvious?

    jschell wrote:
    891860 wrote:
    I am trying to write a Java library around a piece of hardware that currently does not support Java. As the first part of the task, I need to establish a TCP/IP connection between a client and server. I wrote some test code in C that is very simple socket code that can be found on tons of example sites (yes I know Java has built in classes for this, but the connection must exist in the native side).Only reason I can think of for that would be because you need to pass the socket to your C code.
    So given that.
    1. Write C code that creates the socket
    2. Write an API in C that uses 1 to call the library.
    3. Test 1 and 2 via C code.
    After step 3 is complete you do the following.
    A. Determine the business functionality that your java application needs to access via the library. This step does not involve code at all. No C. No java.
    B. Write an API in C that implements the functionality determined in step A. And it will use code from 1/2 as well as needed.
    C. Write code in C to test B.
    After you have completed step 3 and step C then you write JNI and Java.Yes, the case is that the library that Im using for this device is in C, and requires a C socket. I did pretty much the steps that you mentioned. I wrote the basic network code. I wrapped it. Then I wrote a C program to load the .so and test it. It worked fine. When I added the JNI wrapper and Java code to launch it, that is when I had the problems.
    I removed everything but the basic TCP IP code (literally the wrapper that goes into JNI is just the TCP connection code). It still crashed. I then replaced the TCP IP code with another example I found on the net. Same issue. :(
    Edited by: 891860 on 17-Oct-2011 15:55

  • TCP/IP Sockets Comunication by user defined DLL Class

    i will describe it briefly. i need to create a dll class to establish a socket communication and that dll class i should use it between the client App and the server App. but the main task is not done yet which is how to enforce editing to the display
    controls in both Apps by the Class functions. that is it. any help will be appreciated.

    "what i missing here is how to enforce any control on the server App to display the received messages once the client thread send it"
    You cannot enforce this simply by creating a class and/or putting it into a library.  Your MySocket class could generate an event when a message is received but you cannot force client code to do anything about it.  It
    is responsibility of the server code to handle the message and react accordingly.
    "I know i have to specify by coding a specific function on the server side to override another function in the created socket class and that what i'm trying to do."
    Client and server have nothing to do with each other in this case.  Your server side code isn't going to be able to do anything on the client side.  That is the whole reason you're using a client-server architecture.  You can create a client
    class that receives pre-defined messages from the server and handles them.  You can also make these methods virtual so that clients can derive from your client class and do something different for the messages it cares about. 
    //Code on server side
    public class MyServer
    public void SendMessage ( string message )
    //Send message via socket
    //Code in client side type that can be re-used by any client
    public class MyClient
    protected virtual void OnMessageReceived ( string message )
    //Do something with the message
    private void HandleMessagesFromServer ()
    //Infrastructure to monitor socket for messages,
    //determine "message" received and call appropriate
    //method for processing
    //Ex: If server sent a message containing a single string
    OnMessageReceived(stringFromServer);
    //A client may override the behavior for the message(s)
    public class MyCustomClient : MyClient
    protected override void OnMessageReceived ( string message )
    base.OnMessageReceived(message);
    //Notify my UI of the message
    Alternatively you could define a series of events that are raised when messages are received. 
    //Server code doesn't really change
    //Client code uses events instead of virtual methods
    public class MyClient
    public event EventHandler<MessageReceivedEventArgs> MessageReceived;
    private void ProcessMessagesFromServer ()
    //Responsible for watching the socket for messages,
    //translating the messages from the socket and
    //raising the event(s)
    //i.e. Raising an event
    if (MessageReceived != null)
    MessageReceived(this, new MessageReceivedEventArgs(stringFromServer));
    //Clients can handle events instead
    public class SomeUIElement
    //Some initialize method
    private void Initialize ( MyClient client )
    client.MessageReceived += OnMessageReceived;
    private void OnMessageReceived ( object sender, MessageReceivedEventArgs e )
    //Do something with message like display it
    //Note: This is probably not running on UI thread
    Either approach allows a client to react to notifications from the server.  However on the server side all you really need to do is send the appropriate message via the socket.  The client is responsible for reacting to that message in whatever
    way is most appropriate. 
    Michael Taylor
    http://blogs.msmvps.com/p3net

  • JSP code for Alarm

    Hi i need to create an Alarm UI in JSP page. Like what Time CPU,Memory ,concurrent value goes above the marked value(90% usage) should be highlight in different colour like Red. All this data are stored on Oracle database. need to show in an JSP Can some one provide code similar to that thanks

    Saish wrote:
    http://www.google.com/search?q=java+socket+tutorial
    The very first result that came up was Sun's tutorial on sockets: http://java.sun.com/docs/books/tutorial/networking/sockets/
    Writing these in a JSP is generally no different than doing so in Java source file, except you will need to surround the Java code with JSP scriptlet tokens: http://www.jsptut.com/Scriptlets.jsp
    However, I would advise instead writing the socket code in a regular Java object and then invoking that from your JSP. You really don't want to have code in the JSP if you can help it.
    - SaishYou advise to use scriptlets. You know you will have to spend a year or two in purgatory for that!
    Be cool, use a servlet for this.

  • Sockets not closing

    I'm doing some simple socket programming but I'm having trouble getting my sockets to close. I tell them to close but they don't seem to be recognized as closed.
    Here is where I get create my socket:
    {code
    Socket connectionSocket = myWelcomeSocket.accept();
    ChatWindow window = new ChatWindow(connectionSocket);
    (new Thread(new SendToClient(connectionSocket,window))).start();
    (new Thread(new ReceiveFromClient(connectionSocket,window))).start();
    so all of these objects know about the connection
    Here's SendToClients run method:public SendToClient(Socket socket, ChatWindow window)
    try
    myConnectionSocket = socket;
    myOutToClient = new DataOutputStream(socket.getOutputStream());
    myWindow = window;
    catch (IOException e)
    // TODO Auto-generated catch block
    e.printStackTrace();
    public void run()
    while(myConnectionSocket.isConnected())
    //do some stuff
    In ChatWindow I can close the window and I want this to close the connection:public ChatWindow(Socket connectionSocket)
    myConnection = connectionSocket;
    this.addWindowListener(new WindowAdapter()
    public void windowClosing (WindowEvent e)
    try
    myConnection.close();
    catch (IOException e1)
    // TODO Auto-generated catch block
    e1.printStackTrace();
    //other stuff
    When I close the window, it should close the connection but other classes still see the connection as connected.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Yeah this is a TCP thing. If the connection is closed remotely on a non-blocking channel its key will repeatedly be flagged as 'readable' but reading will not return -1 but instead will return 0.
    You could set a counter and assume that a read operation of 0 bytes for x number of times is a closed socket. That should be reasonably safe depending on the application.
    Unfortunately the only real way to know if a socket is closed is to write to it. This will throw an IOException. Ugly but accurate 99.99% of the time. (Never be 100% positive :)
    What I do is write OOB data to the socket to test it. That way even if the other end is still connected and I can't send it random data the socket will silently discard the OOB data. That is unless you have changed the default setting to inline urgent data, in which case the OOB data will be read just like regular data. And having the OOB data discarded down the line doesn't matter, it's the local test we need.
    I simply use something like this:
         * Check if the socket is closed. Ugly but effective.
         * @return True if the socket is closed, false otherwise.
            public boolean isClosed()
                try
                     *NOTE: Using this because normally OOB urgent
                     * data is silently discarded by the socket
                     * however if socket.setOOBInline(true) is used this
                     * won't work as expected.
              chan.socket().sendUrgentData(1);
              return false;
                catch(IOException ex)
                    return true;          
            }

  • Sockets and system freezes

    I have a server written in C that uses sockets to get datagrams from my Java GUI "client" (i.e. a Java program on the same machine). In actuality the bulk of the C code is provided to me as an object file and uses PVM to communicate with a C client (on a different machine) that sends rendering information to it.
    Whenever I add the input sockets on the C server it seems to crash spontaneously and hang my system. Whenever I remove the socket initiliazation code (i.e. no socket code whatsoever) my computer does not crash.
    Does anyone know what's causing this? I know it's something related to sockets because the Java GUI that I invoke from C (without the sockets implemented) does not hang my linux box. It seemingly needs to be quite a big error to freeze linux entirely and not just stall a process in linux.
    What kind of errors using sockets usually cause systems to hang entirely?

    I guess these would be a better questions:
    1. Having conflicting ports will not cause systems to hang correct?
    2. Does anyone have experience with PVM? Would using PVM and adding custom sockets code cause conflicts that would hang a system?

  • Netbios Name query injected into socket connect.

    Folks,
    I have a java application which communicates to a networking device via sockets.
    It was written with J2SE 1.4, I have ported it to 1.5/5.0.
    When issuing a socket connect, I observe that the application/JRE is issuing
    several Netbios Name queries to the device.
    The device is responding with ICMP Destination unreachable.
    After 3 Name queries, the socket connect continues as before (1.4) and the app proceeds as before.
    The problem is that the name queries has introduced a 9 second delay to each connect to the appliance and the app now appears unresponsive.
    This did not happen with JRE1.4. I have made no changes to the socket code.
    Is there a way to stop the name queries?
    The getHostName in the JRE connect code below is causing the name queries.
    java.net.SocksSocketImpl
        protected void connect(SocketAddress endpoint, int timeout) throws IOException {
         SecurityManager security = System.getSecurityManager();
         if (endpoint == null || !(endpoint instanceof InetSocketAddress))
             throw new IllegalArgumentException("Unsupported address type");
         InetSocketAddress epoint = (InetSocketAddress) endpoint;
         if (security != null) {
             if (epoint.isUnresolved())
              security.checkConnect(epoint.getHostName(),
                              epoint.getPort());
             else
              security.checkConnect(epoint.getAddress().getHostAddress(),
                              epoint.getPort());
         if (server == null) {
             // This is the general case
             // server is not null only when the socket was created with a
             // specified proxy in which case it does bypass the ProxySelector
             ProxySelector sel = (ProxySelector)
              java.security.AccessController.doPrivileged(
                  new java.security.PrivilegedAction() {
                   public Object run() {
                       return ProxySelector.getDefault();
             if (sel == null) {
               * No default proxySelector --> direct connection
              super.connect(epoint, timeout);
              return;
             URI uri = null;
    --->>>>>>>> String host = epoint.getHostName();
             // IPv6 litteral?
             if (epoint.getAddress() instanceof Inet6Address &&
              (!host.startsWith("[")) && (host.indexOf(":") >= 0)) {
              host = "[" + host + "]";
             }Mauro Zallocco.

    The resolution of this is to turn off the new proxy server feature in JRE1.5.
    You do this by informing the jre that you do not have a default proxy server.
    This is done with the following lines of code placed somewhere in you application:
    import java.net.ProxySelector;
    ProxySelector.setDefault(null);
    With this, the NetBIOS name queries do not emanate, and we revert back to the 1.4 behavior.
    Mauro Zallocco.

  • How To Avoid Socket Security Erros

    Hi,
    I have to connect to a remote IP camera server from flash through socket connections.
    It is working fine while testing in  Flash IDE, but not working when I upload to my server.
    I know it is due to security restrictions  that you cannot access other domains.
    Kindly suggest is there any other way to connect to the remote server to which u cannot add any cross domain files.
    If it is proxy route, suggest some of them.
    I have tried with RFC2417 socket  posted here
    http://blogs.adobe.com/cantrell/archives/2006/07/a_proxy-savvy_s.html
    I got Bad request error when i use this class.
    One of the friends in this forum suggested java proxy posted here
    http://coderslike.us/2009/01/23/flash-socket-code-and-crossdomain-policy-serving/
    How to connect flash and java ???
    I am trying for a solution for the past 1 month!!!
    Any help is hight appreciated.

    Ur error might be related to "UNSUFFICIENT PERMISSION" at the Server side to create a File or for any other task....check it out
    hope it helps,
    Cheers,
    Manja

Maybe you are looking for

  • How To Work Around Set Up Issue With Time Machine?

    When I attempt to set up an external drive for Time Machine I get this: You do not have appropriate access privileges to save file ".001b63b53d7a" in folder "Time Machine Backups". I have searched for this file and cannot find it. I have deleted any

  • Sun ONE Studio 5 evaluation. JDBC RowSet question.

    I am accessing a MYSQL database using form wizard. I am also using the DataNavaigator. When I use RowSet type: NB CachedRowSet, I can bring in and scroll through existing data, add, change, and delete rows with no problem. When I use NB JDBC RowSet,

  • Scatter Plot

    Does anyone know how to move the x-axis below the title of the chart in Numbers 09? Currently, the x-axis is at the bottom of the graph. I am trying to show a depth correlation so I need the x-axis move. Any suggestions would be great! goal: x-axis h

  • Ise vm upgrade to 1.2

    I have been reading the documentation and just seeking some guidance on this upgrade. I have a standalone ISE on a 32 bit VM. Is the process to perform the upgrade on ISE itself then shut down and change the VM settings? Or change the VM settings and

  • Maintenance Optimizer - ABAP queue check failed

    Hi guys. When running Maintenance Optimizer for a SAP ERP 6.0 EHP4 which has SAP HR 604 installed, the following message is displayed ABAP queue check failed Error       The Installation/Upgrade Package for Add-on SAP_HR rel. 600 is not available. Th