Search code examples
javamultithreadingsocketsserversocket

Detect closed socket


I'm writing a multithreaded server which at the moment just receives a string and send it back capitalized.

My problem is that the server doesn't detect when the connection to the client is lost and the client Handler thread is therefore kept running.

I have a while loop which handles the client requests and I'd like to break out of this loop if the connection is closed/lost.

This is the code of the ClientHandler

try {
            inFromServer = clientSocket.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);

            OutputStream outToServer = clientSocket.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);

            while(!clientSocket.isClosed()){
                if(in.available() > 0) {
                    String str = in.readUTF(); //Should catch EOF
                    System.out.println("[+] From " + clientSocket.getInetAddress() + " received: " + str);
                    String response = str.toUpperCase();

                    out.writeUTF(response);
                }
            }

            System.out.println("[+] Closing client");

        } catch (IOException e) {
            e.printStackTrace();
        }

I have tried to make the while loop like this:

while(!clientSocket.isClosed() && inFromServer.read() != -1)

But this isn't working...

Any suggestions will be appreciated.


Solution

  • Socket.isClosed() will only return true if you have closed the socket. The way you detect that a connection has been closed by the peer is by reading from it. You should not be using in.available(). instead, just read from the socket and you will get an exception when the socket is closed.