【发布时间】:2011-08-01 12:09:56
【问题描述】:
我在 C# 中有一个 TCP 隧道。我需要打开和关闭隧道,这是我在服务器和客户端之间的应用程序。我正在使用它来关闭数据连接以测试另一个应用程序。我必须使用特定的端口。
在第二个、第三个、第 n 个连接上,取决于我等待重新连接的时间,我在绑定我的套接字时收到一个 10048 错误代码 - “地址已在使用中”。关闭套接字时,我确实执行了 ShutDown.Both 和 Close 以希望清除端口,但是当我在命令提示符下执行 netstat 时,我仍然发现端口保存在 TIME_WAIT 中。我还将套接字设置为不逗留。最后,我尝试创建一个循环来检查端口的状态,但它以一个无限循环结束。我认为这是 4 分钟 TIME_WAIT 规则。
我有一个函数来显示一个嵌套查询,我发现当我运行它并检查直到端口从 ESTABLISHED 进入我可以绑定的 TIME_WAIT 时,但是当我使用来自这个查询的相同数据来绑定一个当状态达到 TIME_WAIT 时循环,我得到一个 10048。我的按钮单击是否允许我绑定一个短暂的时间?在 TIME_WAIT 和 ESTABLISHED 之间是否存在状态我正在循环中,而不是当我通过按钮单击执行它时?我读到 TIME_WAIT 应该完全阻止我绑定,但这似乎不是真的。谁能解释一下?
我向各位代码爱好者道歉。没想到这会改变任何事情。我只需要更好地了解港口国。
public bool CheckAvailablePorts()
{
int temp=0;
bool availPort= true;
m_config = new AppConfig();
if (!m_config.initialize())
{
System.Diagnostics.Debug.WriteLine("Error loading configuration file. Exiting...");
return false;
}
else
{
//checking through all the ports that have been set to connect on
foreach (ProxyConfig cfg in m_config.m_proxyConfigs)
{
availPort = true;
temp = cfg.localEP.Port;
DataView dv = FindEstablishedSockets();//returns netstat query
foreach (DataRowView rowView in dv)
{
DataRow row = rowView.Row;
if ((Convert.ToInt32(row["Local Port"].ToString()) == temp) && (row["Status"].ToString().Equals("Established")))
{
System.Diagnostics.Debug.WriteLine("Port: " + temp + " is still locked");
availPort = false;
break;
}
}
}
return availPort;
}
}
//snippet out of a bigger function which checks for availability and then sleeps if false and runs again
bool temp = false;
while (!temp)
{
temp = monitor.CheckAvailablePorts();
System.Threading.Thread.Sleep(2000);
}
System.Threading.Thread.Sleep(3000);
monitor.startApplication(); //starts all the binding
【问题讨论】:
-
在 Windows 上,当您释放端口时,它会停留在 TIME_WAIT 中等待一些可配置的超时。有一个注册表设置,
HKLM/System/CurrentControlSet/Services/Tcpip/Parameters/TCPTimedWaitDelay -
取决于谁关闭Connection,Time_wait可能发生在服务器端或客户端,也许让客户端关心这个?
-
isi.edu/touch/pubs/infocomm99/infocomm99-web 建议对 TCP 进行一些更改以解决此问题。我认为他的想法没有成功,但有一些关于这个问题的细节。
-
您可能不想更改机器范围的时间等待设置,请参阅此处了解我对 TIME_WAIT 的看法:serverframework.com/asynchronousevents/2011/01/…
标签: c# tcp ports netstat time-wait