Add key to a selected keys set

我的梦境 提交于 2019-12-31 05:17:31

问题


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){
    if(key.isReadable()){
        SocketChannel channel = key.channel();
        //read some data
        //respond
        key.interestOps(SelectionKey.OP_WRITE)
        //How to add the key to a selected set?
    }
}

After reading some data I want to respond. It means I need to add OP_WRITE to the key and then add the key to Selected-keys set and then write some content to a channel once the key appeared in a selected-set.

How to add the key to a selected set explicitly?


回答1:


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.



来源:https://stackoverflow.com/questions/44627580/add-key-to-a-selected-keys-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!