Java Socket:How does the client determine whether the socket has been disconnected?

If I close the server socket, how does the client know that the Socket has been disconnected? For instance, look at this image where the reply is null when the socket was disconnected.

1 answer

  • answered 2020-06-27 04:35 Ayush

    You probably have a class implementing Runnable somewhere in your code that acts as the incoming-message-reader in your client code? Something like this, perhaps:

     public class IncomingReader implements Runnable{
            public void run(){
                String message;
                    while ((message = reader.readLine()) != null){
                        System.out.println("read " + message);
                        incoming.append(message + "\n");
                        //incoming is the TextBox where messages are displayed, in this case
                } catch(Exception ex){

    When the socket gets disconnected, an exception will be thrown when you read a message, and the control flow will shift to the catch block. There, I for instance decide to close the client. You could change it to whatever you want to do.

    It's hard to comment further without a minimal reproducible code of your work.