Sunday, September 1, 2013

More NIO Tidbits

A miscellaneous list of interesting things I've found playing with my own NIO code (on a Mac OS X Lion 10.7.5):

Selector.select() and .selectedKeys can return non-zero and non-empty values even if the client has disconnected. They merely represent there is something to do. Maybe data has been buffered and needs reading.

If the state of the client has changed since the last call to Selector.select(), this may not be reflected until the next.

Similarly, SocketChannel.read(...) can return happily return a value greater than 0 and fill your buffer even if the client has long since disconnected. But it can also return -1 if the client has disconnected while at the same time a call to its SelectionKey.isReadable() returns true.

So, SelectionKey.isReadable() can return true even though the client has disconnected (even if it has not written anything) but it can also return false while the client is connected (but has not yet written anything)!

If the client has disconnected, the socket on the server side can still be open and be in a CLOSED_WAIT state. Writing to the associated SocketChannel will not throw an error but unsurprisingly the socket may no longer show up in a netstat after this has been done.

The Socket associated with the SocketChannel may still return true when its isConnected method is called irrespective of whether the client has disconnected. It is returning the state of this socket, not the socket on the client.

No comments:

Post a Comment