tcp connection in TIME_WAIT won't allow reconnect, java

梦想与她 提交于 2019-12-08 12:42:12

问题


After making a tcp connection to a server, I close my linux application and Socket.close() is called.

Checking netstat -pant, I see the connection is in TIME_WAIT status.

This prevents me from making an immediate connection back to the server since I'm using the same port to connect from. Instead, I have to wait for the connection to timeout of the TIME_WAIT status before I can reconnect again.

I've played around -without luck- with the socket methods: set_so_timeout(), set_keepalive(), set_so_linger(), and set_reuseaddr() - exact spelling of the method may not be right in this post.

My question is HOW do I get the connection out of the TIME_WAIT status so I can instantly make a connection again?

Please let me know.

Thanks, jbu


回答1:


The best way to get the connection out of TIME_WAIT is (surprisingly) to wait :-)

That's how TCP/IP works. A session is identified by the tuple (sourceIP, sourcePort, destIP, destPort, protocol) and the reason why you can't re-use it is because there may be packets for it still out in the network somewhere.

TIME_WAIT state is generally twice the maximum packet lifetme and you should not be fiddling with it since that may cause packets to show up from the previous session (which will screw up your current session).

Ideally, you should connect from a different source port, then you will be able to open the session immediately.

Another thing you should watch out for is badly closed sessions. I've always subscribed to the guideline that the client should shut down the session (and shut it down cleanly). This minimizes the possiblity for long-lived half-closed sessions hanging around.



来源:https://stackoverflow.com/questions/1490196/tcp-connection-in-time-wait-wont-allow-reconnect-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!