javasocketchannel

ServerSocketChannel.socket() is still bound after close()


I Used java.nio for server programming and it works fine. When I try to close socket:

    serverChannel.socket().close();

        serverChannel.close();  

    boolean b1 = serverChannel.socket().isBound();   
  boolean b2 =
     serverChannel.socket().isClosed();

and check values, b1 is true and b2 is true. When I run netstat I see that state od port is "LISTENNING" While I was using "old" IO, closing socket did excatly what I expected (netstat did not list port as Listenning).

How can I "unbind" socket without shuting down JVM?


Solution

  • I Got the solution. We have to keep in mind that keys contains serverSocketChannel as well.

    if(this.serverChannel != null && this.serverChannel.isOpen()) {
    
        try {
    
            this.serverChannel.close();
    
        } catch (IOException e) {
    
            log.error("Exception while closing server socket");
        }
    }
    
    try {
    
        Iterator<SelectionKey> keys = this.selector.keys().iterator();
    
        while(keys.hasNext()) {
    
            SelectionKey key = keys.next();
    
            SelectableChannel channel = key.channel();
    
            if(channel instanceof SocketChannel) {
    
                SocketChannel socketChannel = (SocketChannel) channel;
                Socket socket = socketChannel.socket();
                String remoteHost = socket.getRemoteSocketAddress().toString();
    
                log.info("closing socket {}", remoteHost);
    
                try {
    
                    socketChannel.close();
    
                } catch (IOException e) {
    
                    log.warn("Exception while closing socket", e);
                }
    
                key.cancel();
            }
        }
    
        log.info("closing selector");
        selector.close();
    
    } catch(Exception ex) {
    
        log.error("Exception while closing selector", ex);
    }
    

    Does Selector.close() closes all client sockets?