How to close a ServerSocketChannel?

2

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?

    
asked by anonymous 22.09.2015 / 22:24

1 answer

0

I ran a test using the piece of code I posted and checked that the connection is closing correctly. When trying to listen to a port while your service is running, I get the following exception: java.net.BindException: Address already in use: bind , but after five seconds, the service works correctly.

Server:

ServerSocket serverSocket = new ServerSocket(1331);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

Client:

Socket kkSocket = new Socket("localhost", 1331);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
    
12.01.2017 / 19:11