The canonical way of using a Selector
in java NIO is :
ServerSocketChannel
with the SelectionKey.OP_ACCEPT
event type .select
method (which block the thread)in a loop methodOP_ACCEPT
event happened , and the relative AcceptEventHandler
is invoked to accept a SocketChannel
SocketChannel
with the SelectionKey.OP_READ
event type.ReadEventHandler
handle the inputs and then regist the SocketChannel
with a SelectionKey.OP_WRITE
event type. My question is, why don't register three event type at once at the beginning? Does the sequence make any sense?
The canonical way of using a
Selector
in java NIO is:
No it isn't. See below.
why don't register three event type at once at the beginning?
Because you can't. You don't have the accepted channel until you call accept()
, and you don't do that until you have registered OP_ACCEPT and had it fire, and you can't register the accepted channel for anything until you have it.
does the sequence make any sense?
Nothing else would make sense.
NB you don't register OP_WRITE until you've encountered a short or zero-length write. The reason is that it is almost always ready, so the strategy is simply to write when you have something to write, and only use OP_WRITE to tell you when it becomes possible to write again after a short write (which means the socket send buffer was full).