如何检查 TcpClient 连接是否已关闭? [英] How to check if TcpClient Connection is closed?

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

问题描述

我正在尝试使用 TcpClient,并试图弄清楚如何在连接断开时使 Connected 属性显示为 false.

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 状态的描述
维基百科

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 连接是否已关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆