![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e180. Detecting When a Non-Blocking Socket Is Closed by the Remote HostThe 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 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 }
e174. Reading from a SocketChannel e175. Writing to a SocketChannel e176. Using a Selector to Manage Non-Blocking Sockets e177. Creating a Non-Blocking Server Socket e178. Accepting a Connection on a ServerSocketChannel e179. Using a Selector to Manage Non-Blocking Server Sockets
© 2002 Addison-Wesley. |