我怎么能强行关闭的TcpListener [英] How can I forcibly close a 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)
推荐答案
设置绑定到侦听端口前的 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:
SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
这篇关于我怎么能强行关闭的TcpListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!