我有一个使用TcpListener接收消息的Receiver。这包括在Receiver上设置自动重启的选项,以防某些事情导致其锁定。我遇到的问题是在重新启动期间,关闭侦听器后端口没有被释放。我知道Windows可以保持端口打开3到4分钟,所以我会在放弃之前继续检查五分钟。但有时,端口永远不会释放,接收器会停止。
有谁知道如何关闭TcpListener,然后立即使用相同的端口打开一个新的?
我在下面提供了几段代码:
创建监听器
server = new TcpListener(IPAddress.Any, Port);
server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
server.Start();
...
server.BeginAcceptTcpClient(new AsyncCallback(AcceptMessage), server);
停止听众
finally
{
if (server != null)
server.Stop();
server = null;
...
重新启动代码
Stop();
// Check to make sure the port is released
bool isPortInUse = true;
int count = 0;
// End when the port is no longer in use, or after 5 minutes
while (isPortInUse && count++ < 300)
{
bool isAvailable = true;
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
if (tcpi.LocalEndPoint.Port == Port)
{
isAvailable = false;
break;
}
}
if (isAvailable)
isPortInUse = false;
else
System.Threading.Thread.Sleep(1000); // Wait one second
}
if (!isPortInUse)
Start();