本文介绍了如何检查是否TcpClient的连接被关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用TcpClient的玩弄,我试图找出如何使连接属性说假的,当连接断开。

I'm playing around with the TcpClient and I'm trying to figure out how to make the Connected property say false when a connection is dropped.

我试图做

NetworkStream ns = client.GetStream();
ns.Write(new byte[1], 0, 0);

但它仍然不会显示我,如果TcpClient的断开。你会如何​​去这个使用TcpClient的?

But it still will not show me if the TcpClient is disconnected. How would you go about this using a TcpClient?

推荐答案

我不建议你尝试写只是为了测试插座。不要对.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;
}

这篇关于如何检查是否TcpClient的连接被关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:55