Add key to a selected keys set

后端 未结 1 851
时光取名叫无心
时光取名叫无心 2021-01-28 08:07

I\'m writing a NIO server and would like to response on a user request, i.e. write some data to a channel.

Selector selector;
//...
if(selector.selectNow() != 0)         


        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-28 08:46

    You can't. From the Javadoc:

    Keys may not be added directly to the selected-key set.

    You can only remove keys from it.

    But you don't need any of this. If you want to write, just write, and if and only if the write returns zero, register the channel for OP_WRITE and return to the select loop. When and if the channel becomes writable, it will be added to the selected keys set automatically. You don't need to wait for OP_WRITE to do the initial write.

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