Reputation: 18501
Please ignore this question which has been requested to be deleted by the author. Please see the comments for the reason.
The following code always throws
java.net.SocketException: Socket closed
at the last statement (socket.connect(myInetSocketAddress, 6000);
)
Socket socket = new Socket();
socket.connect( myInetSocketAddress, 6000);
//use socket to do some reading
...
socket.close();
socket = new Socket();
//The following is bound to throw java.net.SocketException: Socket closed
socket.connect(myInetSocketAddress, 6000);
If waiting (Sleep()) is added, everything will be fine as following:
Socket socket = new Socket();
socket.connect( myInetSocketAddress, 6000);
//use socket to do some reading
...
socket.close();
Thread.sleep(1000); //critical to prevent java.net.SocketException: Socket closed
socket = new Socket();
//The following works fine after Thread.sleep(1000)
socket.connect(myInetSocketAddress, 6000);
Could anyone shed some light on this?
Upvotes: 2
Views: 355
Reputation: 310884
Why is waiting required after a socket is closed before re-connection?
It isn't.
It isn't the sleep that made any difference here, it is the new Socket()
line.
Clearly your first piece of code isn't an accurate representation. You got SocketException: socket closed
, which indicates that you were trying to re-connect the original socket, so clearly you didn't have the new Socket()
line when you ran it.
This also explains why calling setReuseAddress()
didn't make any difference. That would only help with a BindException,
and you would only get that if you were trying to connect using the same local IP address and port, using the 4-argument connect(),
which you weren't doing.
Upvotes: 1