How to close a Serversocketchannel?

Asked

Viewed 133 times

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 is just a test.

This code should open the connection with 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 door is not released, only if I remove it, but if I remove it I cannot accept customers.

How can I find a way to release the door without having to close the application ?

1 answer

0

I ran a test using the piece of code you posted and verified that the connection is closing correctly. When trying to listen to a door 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 properly.

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()));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.