Server to detect client disconnection "Sockets"

i want to know how it is possible for a server to find out when the client is disconnected at any instance. not only at the time of sending data...
i am writing a server that should communicate with different clients, and i want it to be able to find out if a client suddenly disconnects or crashes, so how can this be done?!
is it this way:
skt.setKeepAlive(true);the problem is that SO_KEEPALIVE checks after 2 hours, which is too much time, how can i change this value????

So, i want to be able to find out if the client is disconnected without waiting to send or receive data.Use a read timeout.
how can i change the value of SO_KEEPALIVEYou can't. It is two hours by default and requires privilege to change it, and changing it is system-wide. So you don't want to do that.
Use a read timeout. Socket.setSoTimeout().

Similar Messages

  • Detecting client disconnects

    What's the best way to detect a client loss of connection? I've heard
    you can register for weblogic.accounting.disconnect events or used the
    workspace destroyMonitor method. Which is preferred? The events method
    concerns me because I don't believe it will be supported in the future
    once JMS takes a foothold. Is this a valid concern? Are there any new
    ways to do this?
    thanks,
    Edwin

    I would suggest you try catching java.net.SocketException (Connection reset
              by peer: socket write error) in you doGet/doPost method. This is not a sure
              way though ...
              --- Igor Zavialov
              "Dylan Taffe" <[email protected]> wrote in message
              news:3a5393d6$[email protected]..
              > Does anyone know of a way to detect client disconnects with servlets?
              Does
              > the contextEventListener or any other event listener get called when a
              > clients kills its connection with the weblogic server?
              >
              >
              

  • Asking about how server can handle client disconnection

    Dear sir/madam,
    i'm doing my final year project and it is about a java client/server big2 game.But now i have a difficulties in dealing with the server side.
    That is about how to take action on the serverside if the client suddenly disconnected.
    I have read many java client/server programming scripts.But all of them doesn't mention this problem.The scrpits only assume the client side never disconnect suddenly.
    I hope if you can give me some suggestions on this problem.

    For my mud written in java, I used TCP/IP for the connections. When a client connects, he gets his own thread. Those threads are held in a vector in a manager class. each tick of the server does a quick run thru the vector and if the current thread/socket its on is null or !isAlive() its remove from the vector(which in turn removes it from getting any more game updates. This removal can be caused by two things. The clients disconnects by accident(kills his game, locks up has an internet connection hiccup, etc.) or he uses the games "quit" method. The quit method calls a method that does any player saving of data, etc then closes the socket, and sets it to null. thus the manager sees this and removes him frm the vecotr list on the next server tick. Seems to work great form a mud and worked really well in a multiplayer applet game I had up for a while.

  • Detect Client Disconnect When using RTMP

    Hello,
    I hava a Java Server and Clients using RTMP. I've read somewhere that I can detect instantly client disconnection when using RTMP. However I cannot find an example code (in Java) that demonstrates this functionality? Can you help me please?

    I am not sure how your client looks, however the lient connect using NetConnection under the hood which spits NetStatusEvents's and you can listen to them ...
    C

  • Detect client disconnection

    Hi.
    My Java Web Service works with ComPorts so I need to close it in a right way when a client disconnects.
    Is there a way to detect in the Web Service when a client disconnects.
    Thank�s you all!!

    So, i want to be able to find out if the client is disconnected without waiting to send or receive data.Use a read timeout.
    how can i change the value of SO_KEEPALIVEYou can't. It is two hours by default and requires privilege to change it, and changing it is system-wide. So you don't want to do that.
    Use a read timeout. Socket.setSoTimeout().

  • RMI detect client disconnect

    Hello, I want to detect when a network disconnect occurs. I implemented a TimerTask that checks every X seconds if the remote object is still bound in the registry, by doing a Naming.lookup(). When I unplug the cable of my computer (to simulate the disconnect), the Naming.lookup() just seems to hang, there is no response... When I plug in the cable again, then I get a response, but this is not the idea... Is there a way to set a timeout or something on this method call?
    thanks

    When I was toying around with chat servers using the RMI Technology, I would have the server keep a vector of RMI Clients (almost like the registry). Then when I went to send a message, I would try to cast the Vector element into the correct type of a client and write the message. If an exception was thrown, I knew the client was not connected any longer and I removed the client from the vector. This approach I have since seen in a lot of documentation on chat servers.
    I haven't tried this but you may try calling the Naming.list () and comparing the values to see if you find a match.
    Hope this helps

  • Detecting Client Disconnect

    I am looking for a way to determine when a client connects and disconnects (especially the latter) from the grid. Two approaches come to mind:
    1) Polling for something that appears/disappears when a client connects or disconnects. The most obvious candidate is a lock. This approach is inefficient because it requires polling. It also raises the issue of how clients are distinguished, although that is not difficult (e.g. - invocable increments a counter which is used as a basis for the key to lock).
    2) Getting a notification when this happens - preferably in-grid. However, I could find no listener for either the client connect/disconnect event or for locking. Likewise, using custom cache implementations (overriding a class and calling it out in the cache config) doesn't seem to provide notification of either locking, or (an alternate approach) the registration of a listener.
    Overriding a cache indeed provides notice of listener registration, but it appear to be a general listener which is feeding some other internal Coherence facility which manages the specific per-client listeners.

    Answering my own question, after research and help from Gene Glyzer:
    There are a couple of ways to do this:
    1) A client can lock a phantom (or real) entry in a cache. When the client member of the cluster goes away, the lock will be released.
    2) Tracking cluster members:
    * Add a listener:*service = CacheFactory.getService("name").addMemberListener(...)*
    * Get the membership information (synchronously guard against listener events):*Set members = service.getServiceMembers()*
    * Use subsequent listener events to adjust the members set.

  • How to detect client socket shutdowns in server socket

    Hi,
    Hoping to get some help with this. I am writing this program that implements a socket server that accepts a single client socket (from a third-party system). This server receives messages from another program and writes them to the client socket. It does not read anything back from the client. However, the client (which I have no control over) disconnects and reconnects to my server at random intervals. My issue is I cannot detect when the client has disconnected (normally or due to a network failure), hence am unable to accept a fresh connection from the client. Here's my code for the server.
    ServerSocket serverSocket = null;
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    try{
              if (serverSocket == null){
                    serverSocket = new ServerSocket(4511);
         clientSocket = serverSocket.accept();
         System.out.println("Accepted client request ... ");
         out = new PrintWriter(clientSocket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
         System.out.println("Input / Output streams intialized ...");          
         while (true){                              
              System.out.println("Is Client Socket Closed : " + clientSocket.isClosed());
              System.out.println("Is Client Socket Connected : " + clientSocket.isConnected());
              System.out.println("Is Client Socket Bound : " + clientSocket.isBound());
              System.out.println("Is Client Socket Input Shutdown : " + clientSocket.isInputShutdown());
              System.out.println("Is Client Socket Output Shutdown : " + clientSocket.isOutputShutdown());
              System.out.println("Is Server Socket Bound : " + serverSocket.isBound());
              System.out.println("Is Server Socket Closed : " + serverSocket.isClosed());
              messageQueue = new MessageQueue(messageQueueDir+"/"+messageQueueFile);
              //get Message from Queue Head (also removes it)
              message = getQueueMessage(messageQueue);
              //format and send to Third Party System
              if (message != null){
                             out.println(formatMessage(message));
                   System.out.println("Sent to Client... ");
              //sleep
              System.out.println("Going to sleep 5 sec");
              Thread.sleep(5000);
              System.out.println("Wake up ...");
    }catch(IOException ioe){
         System.out.println("initSocketServer::IOException : " + ioe.getMessage());
    }catch(Exception e){
         System.out.println("initSocketServer::Exception : " + e.getMessage());
    }I never use the client's inputstream to read, although I have declared it here. After the client is connected (it enters the while loop), it prints the following. These values stay the same even after the client disconnects.
    Is Client Socket Closed : false
    Is Client Socket Connected : true
    Is Client Socket Bound : true
    Is Client Socket Input Shutdown : false
    Is Client Socket Output Shutdown : false
    Is Server Socket Bound : true
    Is Server Socket Closed : false
    So, basically I am looking for a condition that detects that the client is no longer connected, so that I can bring serverSocket.accept() and in and out initializations within the while loop.
    Appreciate much, thanks.

    Crossposted and answered.

  • Server Cannot Detect that the Client is disconnected, why?

    From what I've read, in order to make server "know" that a client is disconnected, you have to make server "write" to client socket to eventually catch an ioexception.
    So I write a simple server program and a simple client program. The server "writes" to the client every 10 secs. Now I start the server and client, I can tell on the client side that for about every 10 secs, the client gets the message.
    Now I terminate the client program. The server still keeps writing to the client. It's my understanding that after 1 min or so I should see an ioexception. However, 10 minutes passed and the server still keeps writing...
    Why is this happening? Did I miss something?

    I think it happens because the port is still open
    even after the client is closed.And you should not
    get IOException when you send a packet over a open
    port.Err, no, you should get a SocketException when you send data to a port which has already been closed or reset by the peer.

  • ServerSocket does not detect a disconnected client

    Hi,
    I have created a serverscoket, which will accept 'n' number of clients and send data to all the connected clients.
    And the server should detect when any client goes down or disconnected from network and give the appropriate message to the use that this particluar client has got disconnected.
    I'm able to detect the disconnected client, when the client application is shut down properly (and the application closes the socket). But while the application is running, when the network card is unplugged, then my server is not able to detect this connection loss, and it continues to send the data to the client without throwing any exception.
    Any help would really be greatly appreciated.
    Thanks,
    Hema

    I Asume you don't mean the ServerSocket but the Socket the ServerSocket accepted, for this Socket you can try using
    acceptedSocket.setKeepAlive (true);This may speed up the disconnection detection depending on the implementation of the keepalive mechanism.
    But it then may be that the connection will be terminated, although the connection is only very slow.
    You have to test out, what is better for your purpose.

  • Client disconnection notification for NIO server

    A server accepts connections from clients and registers accepted channels for reading:
    while (true)
        if (selector.select()>0)
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while(iterator.hasNext())
                SelectionKey opKey = iterator.next();
                iterator.remove();
                if (opKey.isAcceptable())
                    clientSocketChannel = serverSocketChannel.accept();
                    clientSocketChannel.configureBlocking(false);
                    clientSocketChannel.register(selector, SelectionKey.OP_READ);
    . . .One of the server's clients disconnects from it by means of socketChannel.close() while the servert is locked with selector.select() (that is the server have nothing to read from its clients and nobody is connecting to it).Will the server be unlocked when the client performs socketChannel.close()? If so, what notification/exception will the server receive?

    One of the server's clients disconnects from it by means of socketChannel.close() while the servert is locked with selector.select()The select() will immediately return; the corresponding channel will be readable; and the read() will return -1.

  • How Server can read client side SSL certificates through java code?

    My code will be running on server which will be a java class that should read any SSL certificates for the user that is logging in to the application.
    Kindly let me know how it can be achieved ? I have very rare knowldge on Security. how i can read SSL certificates of the client machine.
    Also let me know the possible solutions for above question.

    For my mud written in java, I used TCP/IP for the connections. When a client connects, he gets his own thread. Those threads are held in a vector in a manager class. each tick of the server does a quick run thru the vector and if the current thread/socket its on is null or !isAlive() its remove from the vector(which in turn removes it from getting any more game updates. This removal can be caused by two things. The clients disconnects by accident(kills his game, locks up has an internet connection hiccup, etc.) or he uses the games "quit" method. The quit method calls a method that does any player saving of data, etc then closes the socket, and sets it to null. thus the manager sees this and removes him frm the vecotr list on the next server tick. Seems to work great form a mud and worked really well in a multiplayer applet game I had up for a while.

  • Managing stream between java server and c client

    Hi all
    I'm working on a client/server application.
    Client have been written in C
    Server is in Java.
    The client connect to the server, send a message (unknown size) and wait a response from the server.
    The server on connection start a new thread. This thread try to read data from the socket, using a BufferedInputStream :
    BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
    As far as I dont know the size of the incoming message, i use the folowing algorythme to read data :
        byte[] bytesLus = new byte[1000];
        byte[] tmpBytesLus;
        byte[] tousLesBytes;int nb;
        i = 0;
        tousLesBytes = new byte[0];
        Log.trace(sourceTag,"Lecture des premiers octets");
        nb=in.read(bytesLus,0,bytesLus.length);
        Log.trace(sourceTag,nb+"octets lus");
        while (nb>0){                                                     
            tmpBytesLus = new byte[i+nb];
            System.arraycopy(tousLesBytes,0,tmpBytesLus,0,tousLesBytes.length);
            System.arraycopy(bytesLus,0,tmpBytesLus,tousLesBytes.length,nb);
            tousLesBytes = tmpBytesLus;
            i = i+nb;
            bytesLus = new byte[1000];
            Log.trace(sourceTag,"nb octets lus : " + i);
            if (in.available()>0)
                nb=in.read(bytesLus,0,bytesLus.length);
            else
                nb=0;
    This seemed (but only seemed - i will explain it later) to work fine :
    the client send a 6300 bytes sized msg. Server receive it, treat it and send response back. and this at each try.
    But when i change the log level of the server from TRACE to ERROR (wich have on consequence to accelerate the instruction Log.trace( ... ) the server doesn't work so fine !
    On first try, everything is ok, but on second, client send the same 6300 bytes msg, but server consider receiving only 3000 !
    After debbuging, i found why :
    the reason is the use of :
    if (in.available()>0)
    If you are reading faster than the writer, there is a moment where the stream is in a blocking state for the reader. and in.available return the number of bytes you can read before blocking...
    So my server consider that it reached the end of the message....
    So, after this long introduction, here my question :
    What is the best way to detect the end of a stream ?
    Should I send a special character on the stream and decode it on server ?
    Thank's for your advice.
    Olivier

    Generally, there are n ways of making sure an entire message of unknown size is recieved:
    1. Include some kind of validation criteria at the beginning of the message : checksum, bytecount, etc.
    2. Format the message such that the server can tell when the end is reached (subject to "line noise" problems)
    3. Enable two-way communication between the client and server, so they can work it out as they go.
    4. Use a pre-established protocol that handles all this for you
    5. Close the stream after writing if you only have one message.
    6. etc etc etc.

  • How to control one server with multiple clients via TCP/IP

    I am wanting to control a single server with multiple clients.  Only one client would be active at a time, so there would be no conflict.  I want to use TCP/IP.  So far, I have programmed a cluster that passes data back to the server with no problems.  The challenge come in when a second client is added to the mix.  I have't been able to figure out how to turn each client on and send the appropriate data and then turn it off so it doesn't keep sending the same data to the server. 
    Here are the things that I have considered and did some preliminary testing, but don't really know how to impliment:
    1.  Send a numeric on the front of the cluster packet that tells the server that data is on the way.
    2.  Send a boolean on the front of the cluster packet to somehow turn the server TCP/IP on.
    The problem I have found is that LabVIEW TCP/IP doesn't like to be turned on and off.  If it doesn't get the data it expects, it goes into a reset mode and that kills the response time.
    Any help?

    You should consider implementing a set of simple one-byte commands that can be sent back and forth between the Server and the Clients. You can base all of these ideas off the example in the Example Finder under Networking >> TCP and UDP called Multiple Connections - Server.
    You will have two loops in the server VI: one to wait for new connections, and one to send and receive data from the existing connections. For instance, after one of the clients connects, it can request control of the server to send data to it by sending the character "R" for request. Every time the send/receive loop of the Server executes, the first thing it can do is to check all the existing connections to see if any of the clients have sent a control request ("R"). If so, it will create a buffer (array) of control requests. This could be in the form of Connection IDs or indexes in the array for a particular Connection ID. Your choice.
    After the Server receives a request for contol, if it is not already under control by another client, then it can send a response to the first client on the control request list. For instance, the server could send the first client a "S" command for send. Note that after the clients send their control request, they should execute a TCP Read and wait indefinitely for the server to respond with the one-byte "S" command. Then, once the client in control is finished sending data to the server, it could send the character "X" telling the Server to release it from control.
    The example I mentioned above already does a similar thing. Note how when a client wants to disconnect, they send the letter "Q". You can see this in the Multiple Connections - Client VI. The Server then checks each individual connection to see if it's received this one-byte command, and if it has, it closes the connection to the client. This is what you would want to implement, but instead of having just one command, you'll have to distinguish between a few and build up a buffer of control requests.
    Finally, if a client does decide to disconnect in your application, they could send the command "Q" just like the example above. At this point, close the connection and remove that Connection ID from the array of connections. You will also have to handle the case that this client was in the request control waiting line when it disconnected, in which case you need to delete it from that array as well.
    This will definitely work for you, but it will take some work. Best of luck!
    Jarrod S.
    National Instruments

  • Multiple clients on socket connection

    Hi!
    I understand that it is possible that multiple clients listen to one server (on the same port) and even write to it (then it should be a multi-threaded server).
    But i would like to refuse connectios, if one client is connected. How can I do that?
    In my case I have a (single threaded) server. Now one clients connects. The server waits to receive data from the client and answers, without ever closing the port. that works.
    Now if I connect with a second client, the openicng of the socket in the second client works fine, although the server does not seem to notice the second client. Communication is not possible between the server and the second client, and the server doesn't answer to the first client anymore, although he receives data from it.
    So, since the server does not seem to notice the second client (does not accept the connection) and I don't get an exception at the second client, what can I do?
    Thank you for your help!
    concerned Code (if you want to take a look at it):
    CLIENT:
    socket = new Socket(hostname, echo_port);
    SERVER:
    try
    ServerSocket waitingsocket = new ServerSocket(echo_port);
    try
         socket= waitingsocket.accept();
         System.out.println("Client connected");
         ReaderThread reader = new ReaderThread( this, socket );
         reader.start();          
    catch (Exception e)
    READER:
    public void run()
         while (true)
              try {
                   int bytesRead = inStream.read(inputBuffer,
                   0, inputBuffer.length);
                   readCallback.tcpUpdate(inputBuffer,bytesRead);
              catch (Exception oops)
                   readCallback.tcpUpdate(null,-1);
              

    Just to make sure this is clear: You can NOT have multiple clients on a given socket connection. You CAN have multiple clients connected to a particular port on a given server, but each client will be communicating with the server through a different of socket.
    The usual approach here is to set up a listening ServerSocket on the desired port, call accept() on it, then process the communication from the returned Socket object. This is usually done by spawning a new thread and allowing it to handle the socket communication, while the ServerSocket loops around to another accept() for the next communication.
    Here's an excellent intro to the concepts (the code is really ugly and poorly implemented, but it does a good job of explaining the overall concept). I used this as a starting point, and now (after a whole lot of development) have a pretty sweet extensible web server class that handles template expansion, etc... (I use this as a quick and dirty UI for some of my apps, instead of requiring the user to install a JSP container):
    http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/
    - K

Maybe you are looking for

  • Errors with sdk 1.4.1, but not with 1.3??

    I just upgraded to the j2sdk 1.4.1 yesterday from 1.3, and I'm getting a weird compile time error from an import statement that never used to happen. I'm just importing another class I've made, other imports from java.util etc. work fine, but not cla

  • Video card sees 2 monitors

    I use Win7.  When I look at Control Panel>Hardware and Sound>Devices and Printers, I see icons for 2 monitors and I only have 1.    Why does my video card see 2? The card is an ATI Radeon R4550. John

  • Duplicate alarms in iOS 7 notification centre

    (iPhone 5, iOS 7) I have one alarm set in the clock app. Yet it appears twice in the notification centre: "You have an alarm set for 05:42." "Your alarm is set for 05:42." I've tried deleting the alarm and recreating it. One of the two entries above

  • Problems with library on external HD

    I recently moved my entire itunes library to an external HD. It worked very well for a few weeks but now my mac is not able to recognize the drive. I tried to repair the problem using disk utility but was not able to. I was then prompted to back up a

  • How do i find my iCloud backups

    i need help finding my icloud backups