开发者

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

开发者 https://www.devze.com 2022-12-18 17:23 出处:网络
In Java, when you close a socket, it doesn\'t do anything anymore, but it actually closes the TCP connection after a 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?


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.


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.


If you're running a server, then ServerSocket is the proper solution. It will manage everything better than you doing it by hand through recycling and a host of other optimizations intended for running a server with Java.

Closing the socket disconnects the Java object from the operating system, which means that it isn't taking up any resources outside of the JVM, so it really shouldn't be a problem. But if the minimal overhead from Java's garbage collection/finalization scheme is too big of a burden, then Java isn't a valid solution (since your problem isn't specific to socket programming any more). Although I have to say that an efficient garbage collector is not much worse than explicitly managing memory (and can actually perform better).


'I want them to be closed exactly after closed them not after wasting my time and my resources!' No you don't. You want TCP/IP to work correctly, and the TIME_WAIT state is a critically important part of that. If you're worried about the TIME_WAIT state, the quick answer is to be the one who receives the FIN rather than the one who first sends it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号