1

What's the deference between SocketChannel.register() and SelectionKey.interestOps()?

In the echo NIO server found in this SO question, for every key that is accepted, a register is called for a read op. Then once a message is read, the register is called again for a write op. However, after writing a message, rather than registering another read op it calls key.interestOps(SelectionKey.OP_READ).

Why the difference?

Community
  • 1
  • 1
Saad Attieh
  • 1,396
  • 3
  • 21
  • 42

1 Answers1

3

register() will lose or change the key attachment, and possibly return a new SelectionKey altogether: it isn't specified. Use interestOps() in this situation.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • thanks - just to clarify as I am new to the non blocking model, is this the write pattern for an echo server? Accept connection, call socketChannel.register() to register new socket for reading, in read operation use key.interestOps()? to register write operation and in write operation use key.interestOps()? to once more listen for read? So basically the socketChannel.register() is only called once per connection to register the new socket and from then on further operations are controlled using key.interestOps() to control reads/writes? – Saad Attieh Jan 07 '14 at 21:04
  • No. A channel is almost always ready for writing, so you should just write, with caveats. See my answer [here](http://stackoverflow.com/a/20967805/207421). – user207421 Jan 07 '14 at 22:03