0

I'm trying to find a way to see when a client that is connected to my server has disconnected. The general structure of my code is like this, I have omitted irrelevant sections of my code:

public class Server {

    public static void main(String[] args) {
    ...
        try {
            ServerSocket socket = new ServerSocket(port);
            while (true) {
                // wait for connection
                Socket connection = socket.accept();
                // create client socket and start
                Clients c = new Server().new Clients(connection);
                c.start();
                System.out.printf("A client with IP %s has connected.\n",c.ip.substring(1) );
            }
        } catch (IOException exception) {
            System.out.println("Error: " + exception);
        }
    }

    class Clients extends Thread {
        ...
        public Clients(Socket socket) {         
            clientSocket = socket;
            ip=clientSocket.getRemoteSocketAddress().toString();
            try {
                client_in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                client_out = new PrintWriter(clientSocket.getOutputStream(), true);
            } catch (IOException e) {
                //error
            }
        }
        public void run() {
            ...
            try {
                while (true) {
                    while ((message = client_in.readLine()) != null) {
                    ...
                    }
                }
            } catch (IOException exception) {
                System.out.printf("Client with IP %s has disconnected.\n" , ip.substring(1));
            }
        }
    }
}

Basically what I'm trying at the moment is detecting the disconnection through the catch statement in run(), but the issue with this is it doesn't display the message until I terminate my server.

I have also tried to put my print statement after the while(true) loop but my IDE tells me that code is unreachable.

Is there a way to get my "Client with IP %s has disconnected." to display as soon as the client connection is disconnected? What and where should I be checking?

mane
  • 63
  • 3

1 Answers1

0

what I'm trying to do is detecting the disconnection through the catch statement.

Bzzt. readLine() doesn't throw an exception at end of stream. It returns null. Any exception you catch here is an error, and should be reported as such.

while (true) {
    while ((message = client_in.readLine()) != null) {
        ...
}

The problem is here. You are detecting when the peer disconnects: readLine() returns null and terminates the inner loop. However you have pointlessly enclosed the correct inner read loop in an outer while (true) loop, which by definition can never exit.

Remove the outer loop.

user207421
  • 305,947
  • 44
  • 307
  • 483