如何强制关闭 TcpListener
我有一个通过 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 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在绑定到侦听端口之前设置
SO_REUSEADDR
套接字选项。看起来相应的 .NET 代码是这样的:Set the
SO_REUSEADDR
socket option before binding to the listening port. It looks like the corresponding .NET code is something like:套接字在关闭后一段时间内不被使用是有原因的。
套接字由 4 元组组成:源端口和目标端口、源 IP 和目标 IP。
假设您在客户端正忙于向服务器发送数据时强行关闭套接字。
您等待 5 秒并使用相同的端口重新打开服务器,并且相同的客户端将数据发送到相同的 4 元组,服务器将收到具有错误 tcp 序列号的数据包,并且连接将被重置。
你是在搬起石头砸自己的脚:)
这就是为什么连接会处于 time_wait 状态 2-4 分钟(取决于发行版),直到可以再次使用为止。
需要明确的是,我谈论的是 SOCKET,而不仅仅是侦听 tcp 端口。
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.