Welbert
Welbert

Reputation: 21

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?

Upvotes: 2

Views: 600

Answers (1)

user207421
user207421

Reputation: 310957

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.

Upvotes: 1

Related Questions