10000 concurrent connection using Java NIO

后端 未结 1 457
粉色の甜心
粉色の甜心 2020-12-17 07:10

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

相关标签:
1条回答
  • 2020-12-17 07:34
    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:

    • Register a newly accepted channel for OP_READ only
    • When you have something to write to the channel, just write it
    • If that write returns zero, register the channel for OP_WRITE, save the ByteBuffer you were trying to write, and return to the select loop
    • When OP_WRITE fires on the channel, call write() with the same buffer
    • if that write succeeds and doesn't return zero, register OP_READ again, or at least remove OP_WRITE from the interestOps.

    NB Closing a channel cancels its key. You don't need the cancel.

    0 讨论(0)
提交回复
热议问题