Java LanguageNIO - Networking


Remarks

SelectionKey defines the different selectable operations and information between its Selector and Channel. In particular, the attachment can be used to store connection-related information.

Handling OP_READ is pretty straight-forward. However, care should be taken when dealing with OP_WRITE: most of the time, data can be written to sockets so the event will keep firing. Make sure to register OP_WRITE only before you want to write data (see that answer).

Also, OP_CONNECT should be cancelled once the Channel has connected (because, well, it is connected. See this and that answers on SO). Hence the OP_CONNECT removal after finishConnect() succeeded.