我有一个java.nio.channels.ServerSocketChannel
我初始化如下:java.nio.channels.ServerSocketChannel没有正确关闭
while(true)
{
ServerSocketChannel channel = ServerSocketChannel.open();
InetSocketAddress serverSocket = new InetSocketAddress(host,port);
channel.bind(serverSocket);
SocketChannel ch = channel.accept();
// Later on when I have read off data from a client, I want to shut this
// connection down and restart listening.
channel.socket().close(); //Just trying to close the associated socket
// too because earlier approaches failed
channel.close();
}
当我从客户端发送的第一条消息被成功传递到服务器和客户端程序退出。然后麻烦开始了。当我再次初始化客户端,并尝试建立 在服务器的同一个端口和地址,因为我做了第一次,我得到一个
java.net.BindException:地址已在使用:连接
即使我关闭了关联的通道/套接字。 我一直在更新ServerSocketChannel
和InetSocketAddress
对象,因为由于我的客户端实例在写入后必须关闭,所以我不得不关闭该通道,并且由于在关闭后我无法重新使用通道,所以我必须每次都创建一个新对象。我的理论是,因为channel
参考每次重新分配,孤立的对象变成GC肉,但由于close()方法显然不能正常工作,通道仍然活着,直到GC收集它,我的端口将被占用。 尽管如此,我仍试图在while循环之前保留ServerSocketChannel
和InetSocketAddress
对象的初始化,但这并没有帮助,并且在第一次写入之后发生了同样的异常。
ServerSocketChannel channel = ServerSocketChannel.open();
InetSocketAddress serverSocket = new InetSocketAddress(host,port);
channel.bind(serverSocket);
while (true)
{
SocketChannel ch = channel.accept();
//read from a client
}
为清楚起见,这里是我如何从客户端连接:
SocketChannel ch=SocketChannel.open();
ch.bind(new InetSocketAddress("localhost", 8077));
InetSocketAddress address=new InetSocketAddress("localhost",8079);
//the address and port of the server
System.out.print(ch.connect(address));
ByteBuffer buf=ByteBuffer.allocate(48);
buf.clear();
buf.put("Hellooooooooooooooooooooooooo".getBytes());
buf.flip();
while(buf.hasRemaining()) {
ch.write(buf);
}
ch.close();
这绝对是香草插座中的情况。然而在nio中看起来很奇怪。我会尽量多关注变量名称。 – zafar142003
我不知道我是否知道我在说什么...所以我试了一下,绑定和关闭'ServerSocketChannel'似乎工作。即使是一些沟通。当我擦亮一下时,我会把它链接起来。 – maaartinus
如果在您的试用期中服务器可能会从客户端接收多次的流量(客户端关闭其他连接等后),如果您提到它的完成情况,我将不胜感激。 – zafar142003