ServerSocketChannel.socket() 在 close() 之后仍然绑定
ServerSocketChannel.socket() is still bound after close()
我使用 java.nio 进行服务器编程并且工作正常。
当我尝试关闭套接字时:
serverChannel.socket().close();
serverChannel.close();
boolean b1 = serverChannel.socket().isBound();
boolean b2 =
serverChannel.socket().isClosed();
检查值,b1为真,b2为真。
当我 运行 netstat 我看到状态 od 端口是 "LISTENNING"
当我使用 "old" IO 时,关闭套接字确实如我所料(netstat 没有将端口列为监听)。
如何在不关闭 JVM 的情况下 "unbind" 套接字?
我找到了解决方案。我们必须记住,keys 也包含 serverSocketChannel。
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?
我使用 java.nio 进行服务器编程并且工作正常。 当我尝试关闭套接字时:
serverChannel.socket().close();
serverChannel.close();
boolean b1 = serverChannel.socket().isBound();
boolean b2 =
serverChannel.socket().isClosed();
检查值,b1为真,b2为真。 当我 运行 netstat 我看到状态 od 端口是 "LISTENNING" 当我使用 "old" IO 时,关闭套接字确实如我所料(netstat 没有将端口列为监听)。
如何在不关闭 JVM 的情况下 "unbind" 套接字?
我找到了解决方案。我们必须记住,keys 也包含 serverSocketChannel。
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?