简体   繁体   中英

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.

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:

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. This is a normal part of the TCP/IP protocol to handle delayed packets still wandering around in the network.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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