1

Client:

Open socket:

Socket socket = new Socket(host,port);

Write data:

socket.getOutputStream().write("str");
socket.getOutputStream().flush();

Read data:

response = socket.getInputStream().read();

Close connection and socket:

socket.shutdownInput();
socket.shutdownOutput();
socket.close();

Server:

Socket clientSocket = serverSocket.accept();
message = clientSocket.getInputStream().read();
clientSocket.getOutputStream().write("str2");

clientSocket.isConnected() returned true, and the server does not see that the client is disconnected. How to detect that the client is disconnected?

I'm try use this:

try {
     while (true) {
           message = clientSocket.getInputStream().read();
           clientSocket.getOutputStream().write("str2");
     }
} catch (IOException e) {
     clientSocket.close();
}

But it doesn't work.

silverhawk
  • 569
  • 1
  • 6
  • 14
  • [Related](http://stackoverflow.com/questions/155243/why-is-it-impossible-without-attempting-i-o-to-detect-that-tcp-socket-was-grac?lq=1) [questions](http://stackoverflow.com/questions/151590/java-how-to-detect-a-remote-side-socket-close) which discuss how to detect that socket was closed (or actually why it is not possible to detect reliably). – Oleg Estekhin May 19 '14 at 12:23

1 Answers1

1

A common approach is that the client sends a "QUIT" message to the server. The server will then close it's socket.

The other approach is to do I/O on the server socket and catch the exceptions that you'll get when the client is gone.

The latter approach has a couple of drawbacks:

  • It will take some time for the server to give up trying to reach the client (that can take 2 minutes)
  • The error message might not always be the same. Usually, you'll just get a SocketException with the error message from your OS.
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820