tags:

views:

72

answers:

3

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 ?

A: 

Try

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

Paste error message or/and full stack trace.

iddqd
ok. i'll try that
mohamida
A: 

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.

Devon_C_Miller
ok thnx. i'll try that
mohamida
A: 

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.

Darron
i don't have the server code, nor the server in front of me (it's in another town). So how can i make things work fine ? (because i don't see any code :s )
mohamida