How can I forcibly close a TcpListener

冷暖自知 提交于 2019-12-06 05:36:06

问题


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 service 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)


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/2992568/how-can-i-forcibly-close-a-tcplistener

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