zoukankan      html  css  js  c++  java
  • TCP通信过程中时时监测连接是否已断开

    贴出主要代码:


      private void ReceiveData(object cUserData)
      {
       User cUser=(User ) cUserData;
                //连接断开标志
       bool closed=false;
       byte[] flagbyte=new byte [1];
       while (!closed )
       {
        try
        {
                        //检测是否有课接收的数据
         if(cUser.client.Available>0)
         {
          byte[] bytes=new byte [cUser.client.Available ];
          cUser.netStream.Read (bytes,0,bytes.Length );
         }
                        //监测连接是否存在
         if(cUser.client.Client.Poll (0,SelectMode.SelectRead))
          closed=int.Equals(cUser.client.Client.Receive (flagbyte,SocketFlags.Peek),0);       
        }
        catch { 
         closed =true;
         System.Diagnostics.Debug.WriteLine ("断开连接!");
         cUser.Close ();
        }     
        Thread.Sleep (1);
       }
      }

           
            public class User
            {
                public string cName { get; set; }
                public TcpClient client { get; set; }
                public NetworkStream netStream { get; set; }
                public User(TcpClient _client)
                {
                    this.client = _client;
                    this.netStream = client.GetStream();
                }
                public void Close()
                {
                    netStream.Close();
                    client.Client.Close();
                    client.Close();
                }
            }

  • 相关阅读:
    gcc 工作流程和常用参数
    解决webstorm卡顿问题,下面详细设置方法,使得webstorm快速打开
    使用vue 3.0 初始化vue脚手架
    vue父组件更新,子组件也更新的方法
    vue 父子组件渲染
    数组对象去重 reduce()
    webstorm 点击右上角运行run 启动vue项目
    寻找的常用webstorm快捷键
    mORMot使用基础1(转)
    win7共享win10打印机提示无法连接到打印机 错误 bcb
  • 原文地址:https://www.cnblogs.com/teyond/p/2491213.html
Copyright © 2011-2022 走看看