Detecting When a Non-Blocking Socket Is Closed by the Remote Host

The only way to detect that the remote host has closed the connection is to attempt to read or write from the connection. If the remote host properly closed the connection, read() will return -1. If the connection was not terminated normally, read() and write() will throw an exception.

When using a selector to process events from a non-blocking socket, the selector will try to return an OP_READ or OP_WRITE event if the remote host has closed the socket.

try { // Read from socket int numBytesRead = socketChannel.read(buf); if (numBytesRead == -1) { // No more bytes can be read from the channel socketChannel.close(); } else { // Read the bytes from the buffer } } catch (IOException e) { // Connection may have been closed } try { // Write to socket int numBytesWritten = socketChannel.write(buf); } catch (IOException e) { // Connection may have been closed }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.