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's just a test.
This code should open the connection to port 1331, and after 5 seconds running it should close the connection, releasing the port for use. However, if I use this line:
serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
The port is not released, only if I remove it, but if I remove I can not accept clients.
How can I fix the door without having to close the application?