如何检查在C#中是否连接/断开套接字? [英] How to check if a socket is connected/disconnected in C#?

查看:559
本文介绍了如何检查在C#中是否连接/断开套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果其他主机在断开连接时没有向您发送数据包,则如何检查网络套接字(System.Net.Sockets.Socket)是否仍然连接(例如因为它不正常地断开连接)?

解决方案

由于 Paul Turner 回答 Socket.Connected 不能在这种情况下使用。您需要轮询连接,每次查看连接是否仍然活动。这是我使用的代码:

  bool SocketConnected(Socket s)
{
bool part1 = s。 Poll(1000,SelectMode.SelectRead);
bool part2 =(s.Available == 0);
if(part1&& part2)
return false;
else
return true;
}

它的工作原理如下:




  • s.Poll 如果



    • 正在连线,且有资料可供阅读

  • >
  • s.Available 返回可供阅读的字节数


  • $ b

    • 没有可读的数据,因此连接无效
    • ul>

      How can you check if a network socket (System.Net.Sockets.Socket) is still connected if the other host doesn't send you a packet when it disconnects (e.g. because it disconnected ungracefully)?

      解决方案

      As Paul Turner answered Socket.Connected cannot be used in this situation. You need to poll connection every time to see if connection is still active. This is code I used:

          bool SocketConnected(Socket s)
          {
              bool part1 = s.Poll(1000, SelectMode.SelectRead);
              bool part2 = (s.Available == 0);
              if (part1 && part2)
                  return false;
              else
                  return true;
          }
      

      It works like this:

      • s.Poll returns true if
        • connection is closed, reset, terminated or pending (meaning no active connection)
        • connection is active and there is data available for reading
      • s.Available returns number of bytes available for reading
      • if both are true:
        • there is no data available to read so connection is not active

      这篇关于如何检查在C#中是否连接/断开套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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