Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a socket close immediately, bypassing the timeout period?

In Java, when you close a socket, it doesn't do anything anymore, but it actually closes the TCP connection after a timeout period.

I need to use thousands of sockets and I want them to be closed immediately after I close them, not after the timeout period, which wastes my time and my resources. What can I do?

like image 661
Shayan Avatar asked Feb 02 '10 21:02

Shayan


2 Answers

I found out that by using socket.setReuseAddress(boolean), you can tell the JVM to reuse the port even if it's in the timeout period.

like image 121
Shayan Avatar answered Oct 07 '22 23:10

Shayan


You are probably seeing sockets in TIME_WAIT state. This is the normal state for a socket to enter on the side of the connection that does the 'active close'. TIME_WAIT exists for a very good reason and so you should be careful of simply reusing addresses.

I wrote about TIME_WAIT, why it exists and what you can do about it when writing servers here on my blog: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html

In summary, if you can, change the protocol so that your clients enter TIME_WAIT.

like image 41
Len Holgate Avatar answered Oct 07 '22 23:10

Len Holgate