Esempio n. 1
0
 private void ConnectTask(string host, TcpClient client)
 {
     Task.Factory.StartNew(() =>
     {
         OnConnect?.Invoke(host);//委托:已连接
         while (client.Connected)
         {
             try
             {
                 TcpDataModel model = TcpStreamHelper.Read(client);
                 if (model != null)
                 {
                     if (model.Type == int.MaxValue)
                     {
                         //返回心跳
                         Write(new TcpDataModel()
                         {
                             Type = int.MaxValue
                         });
                     }
                     else
                     {
                         ReceiveMessage(host, model);//委托:接收消息
                     }
                 }
             }
             catch { }
             //Sleep.S(1);
         }
         client.Close();
         OnDisconnect?.Invoke(host);//委托:断开连接
     });
     //lstn.BeginAcceptTcpClient(new AsyncCallback(acceptCallback), lstn);
 }
Esempio n. 2
0
        private void ConnectTask(string host, TcpClient client)
        {
            DateTime HeartbeatTime = DateTime.Now;

            //发送心跳
            Task.Factory.StartNew(() =>
            {
                while (client.Connected)
                {
                    TcpDataModel model = new TcpDataModel()
                    {
                        Type = int.MaxValue
                    };
                    TcpStreamHelper.Write(client, model);

                    Sleep.S(5);
                    //if (DateTime.Now.AddSeconds(-10) > HeartbeatTime)
                    //    client.Close();
                    Sleep.S(5);
                }
            });
            //接收消息
            Task.Factory.StartNew(() =>
            {
                OnConnect?.Invoke(host);//委托:已连接
                while (client.Connected)
                {
                    try
                    {
                        TcpDataModel model = TcpStreamHelper.Read(client);
                        if (model != null)
                        {
                            if (model.Type == int.MaxValue)
                            {
                                //过滤心跳
                                HeartbeatTime = DateTime.Now;
                            }
                            else
                            {
                                ReceiveMessage(host, model);//委托:接收消息
                            }
                        }
                    }
                    catch { }
                    //Sleep.S(1);
                }
                client.Close();
                Clients_Del(host);
                OnDisconnect?.Invoke(host);//委托:断开连接
            });
        }