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

In Java, when you close a socket, it does nothing else, but actually closes the TCP connection after a period of time.

I need to use thousands of sockets, and I want them to be closed right after I closed them, and not after a timeout that takes my time and my resources. What can I do?

+6
java timeout sockets
source share
4 answers

I found out that with socket.setReuseAddress(boolean) you can tell the JVM to reuse the port, even if it is in the waiting period.

+5
source share

If you are using a server, then ServerSocket is the right solution. It will manage everything better than you do it manually, using processing and many other optimizations designed to work the server with Java.

Closing the socket disconnects the Java object from the operating system, which means that it does not take any resources outside the JVM, so this really should not be a problem. But if the minimum overhead from the Java garbage collection / completion scheme is too high, then Java is not an acceptable solution (since your problem is no longer specific to socket programming). Although I have to say that an efficient garbage collector is not much worse than explicit memory management (and can actually work better).

+3
source share

You are probably seeing sockets in TIME_WAIT state. This is the normal state for connecting a socket on the connection side, which performs an “active close”. TIME_WAIT exists for a very good reason, so you should be careful when reusing addresses.

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

In general, if possible, change the protocol so that your clients log on TIME_WAIT .

+3
source share

"I want them to be closed as soon as they have closed them after they have spent my time and my resources!" No no. You want TCP / IP to work correctly, and the TIME_WAIT state is a critical part of this. If you are worried about the TIME_WAIT state, the quick answer will be the one who receives FIN, and not the one who sends it first.

+1
source share

All Articles