当我将 selector.select() 注册到 SocketChannel 并在单独的线程中关闭 SocketChannel 的对等体时,selector.select() 返回,并且设置了该 channel 的 READ 操作。如果我有一个 ServerSocketChannel 注册到选择器,并且我关闭了 ServerSocketChannel,selector.select() 不会返回。无论如何我可以检测到 ServerSocketChannel 在 selector.select() 中被阻止时已关闭?
我尝试使用 selector.wakeup() 并遍历键集(不是选定的键),并查看该组中是否有任何未打开的 channel ,但是一旦在 ServerSocketChannel 上完成关闭,它从选择器中注销,因此它不在 select.keys() 集合中。
最佳答案
Is there anyway i can detect that the ServerSocketChannel was closed while being blocked in selector.select()?
如果您希望 selector.select()
返回,以便您可以在选定的键中提取关闭的 channel ,则否。正如文档所说
It returns only after at least one channel is selected, this selector's wakeup method is invoked, or the current thread is interrupted, whichever comes first.
因为没有像OP_CLOSE
这样的兴趣操作,所以让select
方法在 channel 关闭时返回的唯一方法是唤醒
明确。但是 key 被隐式取消。
无论如何,对于封闭的 channel ,您无能为力。
此外,EPollSelectorProvider
正在代理对底层 epoll
的调用,它也没有您想要的事件。 http://man7.org/linux/man-pages/man2/epoll_ctl.2.html
关于java - 在 selector.select() 中检测 ServerSocketChannel 何时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54794273/