I wrote a Server(similar to one here) and Client code using Java nio.
I am trying to achieve as many connections as possible. From previous suggestions I slowed down
socketChannel.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ);
This is incorrect usage. Your selector will spin, as OP_WRITE
is almost always ready, except at the rare times when the socket send buffer is full. This is why you're not processing OP_ACCEPT
as fast as you could. You're busy processing OP_WRITE
at times when you have nothing to write.
The correct way to use OP_WRITE
is as follows:
OP_READ
onlyOP_WRITE
, save the ByteBuffer
you were trying to write, and return to the select loopOP_WRITE
fires on the channel, call write()
with the same bufferOP_READ
again, or at least remove OP_WRITE
from the interestOps
.NB Closing a channel cancels its key. You don't need the cancel.