简体   繁体   中英

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. 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. It's documented somewhere rather obscure in the Javadoc that I can never find when I need it. So you need to call select() with a short timeout, say five seconds, and do nothing if it returns zero. Or, do whatever housekeeping may arise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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