I have a problem, I've developed a Client and Server wrapper for my personal use, but unfortunately due to insufficient knowledge in network programming, I have TIME_WAIT problems during connect on the client. My client tries to make multiple connections to the same host within short period of time now, I have found out that the main reason for that is because I'm trying to reuse the socket and it goes to TIME_WAIT state because I'm closing the connection without graceful shutdown. I would like to know the correct pattern to close connection using .NET sockets in case I'm using 'Async' APIs intensively i.e. functions like ConnectAsync, AcceptAsync, SendAsync, ReceiveAsync, DisconnectAsync (DisconnectAsync - reuses socket)
-
If you using tcp socket it has some default in windows see http://support.microsoft.com/kb/158474 for details, and if your clients are not thin client I suggest you use WCF over tcp instead of this. – Saeed Amiri Nov 29 '10 at 17:46
2 Answers
I have found out that it is impossible to prevent TIME_WAIT. Either server or client will have the problem any way, depending only on who initiates a closure of the connection first. If it's the client who closes the connection, there will be no TIME_WAIT on server. If it's the server who closes first, than there will be no TIME_WAIT on client. So the only option that is left to do is using SO_REUSEADDR, but in this case it is still impossible to use the reused address for contacting previously disconnected host

- 14,873
- 15
- 79
- 132
-
Bit of an old thread... but see this, as it works for me in preventing TIME_WAIT: http://stackoverflow.com/questions/40785598/to-close-the-socket-dont-close-the-socket-uhmm – cogumel0 Nov 24 '16 at 12:36
You can use SO_REUSEADDR on the socket to get around this. See Socket.SetSocketOption for details, it's the ReuseAddress
option you need to set.
By the way you don't really mean reuse the socket do you? once you get an error, you have to close it and open a new one.

- 53,498
- 9
- 91
- 140
-
Using SO_REUSEADDR is not an option http://www.unixguide.net/network/socketfaq/4.5.shtml – Lu4 Nov 30 '10 at 08:08
-
@Lu4 Why? I don't see anything in either link saying that it should be avoided, only that the implications need to be understood. Eg it's crucial if you want to implement P2P TCP connections from behind a NAT. – Basic Aug 14 '13 at 15:50