简体   繁体   English

Java - 关闭 ServerSocketChannel

[英]Java - Closing a ServerSocketChannel

I have the following code:我有以下代码:

 Selector socketSelector = SelectorProvider.provider().openSelector();
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
serverChannel.socket().bind(new InetSocketAddress(1331));

new Thread() {
    @Override
    public void run() {
        try {
            Thread.sleep(5000);
            serverChannel.close();

        } catch (InterruptedException | IOException ex) {
        }
    }
}.start();

Note: The code is not complete, it is only a test.注意:代码并不完整,只是一个测试。

This code should open the connection port 1331, and after 5 seconds running should close the connection by releasing the port to use.此代码应打开连接端口 1331,运行 5 秒后应通过释放端口来关闭连接以供使用。 However, if I use this line:但是,如果我使用这一行:

serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);

the port is not released, only if I remove, and if I remove can not accept customers.端口是不释放的,只有我删除,如果我删除不能接受客户。

How can I find a way to release the port without having to close the application?如何找到一种无需关闭应用程序即可释放端口的方法?

SelectableChannels that are registered with a Selector have deferred closes that only take effect the next time select() is called.使用Selector注册的SelectableChannels具有延迟关闭,仅在下次调用select()时生效。 It's documented somewhere rather obscure in the Javadoc that I can never find when I need it.它记录在 Javadoc 中某个相当晦涩的地方,我在需要时永远找不到。 So you need to call select() with a short timeout, say five seconds, and do nothing if it returns zero.所以你需要在很短的时间内调用select() ,比如 5 秒,如果它返回零则什么都不做。 Or, do whatever housekeeping may arise.或者,做任何可能出现的内务处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM