问题
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