我正在尝试实现 NIO-server,但对 SelectionKey
有疑问。假设我们提取了一些可供读取的 key 。像这样:
SelectionKey key;
//...
SocketChannel c = (SocketChannel) key.channel;
//read from c
但是我们从 channel 中读取的内容不足以生成完整的数据包
。所以我将一些对象附加到键
上。
问题:什么时候应该从选择器
中删除key
?当我阅读完整的Packet
时?或者每次我应该重新注册 channel 时,从 Selector
中删除 key 并将收到的数据重新附加到新注册的 SelectionKey
上?
最佳答案
When should I remove the key from a Selector?
当您不再对其 channel
中的事件感兴趣时。这是很少见的。大多数情况下,您只需关闭Channel
,这会自动取消SelectionKey
。
When I read the complete Packet?
不,为什么?
Or every time I should re-register the channel, delete the key from Selector
不,为什么?如果您有兴趣从 channel 读取事件,为什么这种兴趣会停止,直到您关闭 channel
?除了您对该 channel 进行短写入的情况之外,在这种情况下您当然应该停止阅读它的兴趣:但您可以通过如下操作 interestOps
来做到这一点。
and reattach data that was received to the newly registered SelectionKey?
我不知道这意味着什么。确实没有理由为现有 channel 注册新的 SelectionKey
。只需尝试一下它的 interestOps
,如果您出于某种原因根本不感兴趣,可以将它们设置为零。
关于java - 从选择器中移除按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45588886/