且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否TcpClient的连接被关闭?

更新时间:2023-02-05 23:20:55

我不建议你尝试写只是为了测试插座。不要对.NET的Connected属性接力无论是。

I wouldn't recommend you to try write just for testing the socket. And don't relay on .NET's Connected property either.

如果你想知道,如果远程端点仍处于活动状态,您可以使用TcpConnectionInformation:

If you want to know if the remote end point is still active, you can use TcpConnectionInformation:

TcpClient client = new TcpClient(host, port);

IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections().Where(x => x.LocalEndPoint.Equals(client.Client.LocalEndPoint) && x.RemoteEndPoint.Equals(client.Client.RemoteEndPoint)).ToArray();

if (tcpConnections != null && tcpConnections.Length > 0)
{
    TcpState stateOfConnection = tcpConnections.First().State;
    if (stateOfConnection == TcpState.Established)
    {
        // Connection is OK
    }
    else 
    {
        // No active tcp Connection to hostName:port
    }

}
client.Close();

另请参见:

TcpConnectionInformation MSDN上

IPGlobalProperties 的MSDN上

说明TcpState美国

上的Netstat ***

See Also:
TcpConnectionInformation on MSDN
IPGlobalProperties on MSDN
Description of TcpState states
Netstat on Wikipedia

和这里是作为TcpClient的扩展方法。

And here it is as an extension method on TcpClient.

public static TcpState GetState(this TcpClient tcpClient)
{
  var foo = IPGlobalProperties.GetIPGlobalProperties()
    .GetActiveTcpConnections()
    .SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));
  return foo != null ? foo.State : TcpState.Unknown;
}