Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to tell if a socket has been disconnected (Java)
    text
    copied!<p>I've read <a href="https://stackoverflow.com/questions/151590/java-how-to-detect-a-remote-side-socket-close">several</a> <a href="https://stackoverflow.com/questions/10240694/java-socket-api-how-to-tell-if-a-socket-has-been-closed">questions</a> about this on stack overflow already, but none of them has provided me with an elegant solution.</p> <p>I know that calling <code>isConnected()</code> and <code>isClosed()</code> on the <code>Socket</code> is useless because it returns the local connection state (if the server is connected - not if the client is connected, as I want).</p> <p>I also can't simply call <code>if(socket.getInputStream().read()==-1)</code>* because that would only account for the end of the stream (EOS) being reached - i.e., the client didn't send a message recently. This doesn't at all indicate that the client has disconnected however.</p> <p>I'm considering just having the client send a message to the server letting it know it's disconnecting just before it closes the socket, but I'm wondering if there's a simpler solution I'm missing - wanting to know the connection state of the remote socket is a fairly commonplace desire. Thanks.</p> <p>*not to mention the fact that <a href="http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read%28%29" rel="nofollow noreferrer">InputStream#read()</a> is an abstract method, I'm using <a href="http://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html" rel="nofollow noreferrer">DataInputStream</a> for data read methods (i.e. readInt(), readByte(), etc.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload