简体   繁体   English

调用socket.close()时套接字未关闭

[英]Socket not closing when calling socket.close()

I found the same problem in this post , but i think it wasn't solved. 我在这篇文章中发现了相同的问题,但我认为它没有解决。

i'm going to be brief, this is my code: 我要简短一点,这是我的代码:

try {
Socket pacConx = new Socket(ip, Integer.parseInt(port));
DataInputStream  dataIn = new DataInputStream(pacConx.getInputStream());
DataOutputStream dataOut = new DataOutputStream(pacConx.getOutputStream());

while(){...}
} catch (IOException e) {
    logger.fatal("error", e);
}finally{
    if (dataIn != null) {
           dataIn.close();
     }
     if (dataOut != null) {
            dataOut.close();
     }
      if (pacConx != null) {
            pacConx.close();
      }
}

First, i connect to the server using the code above, and it succeed. 首先,我使用上面的代码连接到服务器,并且成功。 But, when i try to REconnect to the same server and port after a while, i cannot reconnect. 但是,当我尝试在一段时间后重新连接到同一服务器和端口时,我无法重新连接。 Apparently the first socket is still "alive" in the serverSide. 显然,第一个套接字在serverSide中仍然是“活动的”。

is the a solution to my peoblem ? 是解决我的问题的办法吗?

Is there a way that i can close the other "alive" socket ? 有没有办法我可以关闭另一个“活动”套接字?

Try 尝试

...
dataOut.flush();
dataOut.close();
...

Paste error message or/and full stack trace. 粘贴错误消息或/和完整堆栈跟踪。

You need to initiate an orderly disconnect. 您需要启动有序的断开连接。 After calling flush on the streams, and before calling close on the socket, add this: 在流上调用flush之后,然后在套接字上调用close之前,添加以下内容:

pacConx.shutdownInput();
pacConx.shutdownOutput();

That tells the remote end you're finished and allows it to dismantle the port without waiting to make sure there isn't data still in transit. 这告诉远端您已经完成,并允许其拆除端口,而不必等待确保没有数据在传输中。

For about 2-4 minutes after you close the socket it will hang in "CLOSE_WAIT" state on the server. 关闭套接字后大约2-4分钟,它将在服务器上挂起,处于“ CLOSE_WAIT”状态。 This is a normal part of the TCP/IP protocol to handle delayed packets still wandering around in the network. 这是TCP / IP协议的正常部分,用于处理仍在网络中徘徊的延迟数据包。

This should be handled by your server code. 这应该由您的服务器代码处理。 Is it unbinding its listen socket while handling a request and trying to re-establish it after the close? 它在处理请求并尝试在关闭后重新建立请求时是否解除其侦听套接字的绑定? If so, it should either leave the listen up during processing or re-establish it with a SO_REUSEADDR option. 如果是这样,它应该在处理期间退出侦听,或者使用SO_REUSEADDR选项重新建立它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM