How can I forcibly close a TcpListener
I have a service which communicates through tcpListener. Problem is when the user restarts the service - an "Address already in use" exception is thrown, and the servic开发者_如何学JAVAe cannot be started for a couple of minutes or so.
Is there's any way of telling the system to terminate the old connection so I can open a new one? (I can't just use random ports because there is no way for the service to notify the clients what is the port, so we must depend on a predefined port)
Set the SO_REUSEADDR
socket option before binding to the listening port. It looks like the corresponding .NET code is something like:
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
There is a reason sockets are not used for some time after they are closed. A Socket is comprised of a 4 tuple, Source and Dest Port, Source and Dest IP.
Let's say you close a socket forcefully, while the client was busy sending data to the server. You wait 5 seconds and re-open the server with the same Port, and the same client sends data to the same 4 tuple, the server will get packets with wrong tcp sequence numbers, and the connections will get reset.
You are shooting yourself in the foot :)
This is why connections have a time_wait status for 2-4 minutes (depending on distro) until they can be used again. Just to be clear, i'm talking about SOCKETs and not just the listening tcp port.
精彩评论