问题
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