Java Socket Api: How to Tell If a Connection Has Been Closed

Socket isClosed() returns false after client disconnected

There is no "disconnect" with TCP. A peer can only indicate that it does not want to send anything more (send FIN) but this does not mean that it does not want to receive anything. The other end only realizes that read is unwanted too once it tries it and gets a RST back.

If you take the "don't want to read" as an indicator that the client closed (you might if the application protocol is this way) then you can test if the peer "disconnected" by simply reading from the socket. The system call then returns no error but 0 bytes and this means that there will be no more data from the peer. In Java this case gets translated into an EOFException.

Apart from that a socket does not get closed automatically - only explicitly. isClosed only returns true once the socket is explicitly closed on your local end, not the peer's end. And isConnected will also not tell you if the other end "disconnected", it will only tell you if your end did connect to the peer.

See also Java Socket API: How to tell if a connection has been closed?.

Checking if socket is still open

Just set a read timeout with Socket.setSoTimeout(). Set it to higher than the expected request interval, say double that. If it expires, you will get a SocketTimeoutException: close the socket.

Contrary to some of the comments, isConnected(), isBound(), isClosed(), etc. are no use for this. They tell you whether you connected, bound, closed, etc. the Socket. Not about the state of the connection.



Related Topics



Leave a reply



Submit