我是 nio 套接字的新手,我已经使用 nio 套接字编写了一个服务器,现在我正在尝试编写关闭钩子(Hook)以确保通过清理资源正常退出。
我的问题是 Selector.close()
方法会关闭所有客户端套接字吗?如果没有,请告诉我如何在没有单独的客户端套接字列表的情况下访问所有客户端套接字。
Java Doc 说 selector.close()
方法如下
Closes this selector.
If a thread is currently blocked in one of this selector's selection methods then it is interrupted as if by invoking the selector's wakeup method.
Any uncancelled keys still associated with this selector are invalidated, their channels are deregistered, and any other resources associated with this selector are released.
If this selector is already closed then invoking this method has no effect.
After a selector is closed, any further attempt to use it, except by invoking this method or the wakeup method, will cause a ClosedSelectorException to be thrown.
上面的描述使用了“注销”这个词,给人的感觉是它没有关闭套接字,只是从选择器中删除了它们的映射。
最佳答案
不,它只关闭选择器。
在关闭选择器之前,您可以通过 Selector.keys() 访问所有已注册的套接字键。
关于java - Selector.close() 是否关闭所有客户端套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24543675/