Java Socket Server – Clients Disconnecting (Ungracefully)

If you’re writing a java socket server you’ll need to detect when a client disconnects — even if they don’t have the courtesy to disconnect gracefully. This is especially annoying if you’re sending the client socket a lot of streaming data and the client just stops listening without saying a word.

If you’re using an PrintStream to write data to the socket, the way to check this is to check the result from PrintStream.checkError(). If its false, the client disconnected. I’m assuming other output streams will have similar functionality.

If the client doesn’t disconnect gracefully, these things may still occur:

  • Socket.isConnected() may return true
  • Socket.isClosed() may return return false
  • Socket.isInputShutdown() may return false
  • Socket.isOutputShutdown() may return false

I just wasted an hour figuring this out.. Hopefully it will help someone.

Monday, June 11th, 2012 Uncategorized

Leave a Reply

Psst.. There is no more.