I’m doing some network programming in Java. in a loop I open a socket , send some data and close it. but I get the exception of “connection already in use” . I guess that happens since I use a same port at each repetition of the loop. how long does it take for the OS (Ubuntu 11.10) to close the socket and free the port? thanks
the simplified code look like this
while(true){
Socket clientSocket = new Socket("localhost", 5000);
PrintWriter outToServer = new PrintWriter( clientSocket.getOutputStream(),true);
outToServer.println ("Hi") ;
clientSocket.close();
}
It can take quite a while (e.g. up to 3 minutes if there is unsent data)
In your case you are using a different local port (same remote port doesn’t matter) each time so it shouldn’t matter.
BTW: Creating a new connection is pretty expensive, I would try to re-use a connection rather than opening a new one each time. In the example above it could be as much as 1000x faster. 😉