Esempio n. 1
0
 /// <summary>
 /// 同步连接到一个IP
 /// </summary>
 /// <param name="strIp">IP地址</param>
 /// <param name="nPort">端口</param>
 /// <param name="timeOut">超时</param>
 /// <returns>成功:true;失败:false</returns>
 public bool Connect(string strIp, UInt16 nPort, int timeOut)
 {
     m_serverIP   = strIp;
     m_serverPort = nPort;
     m_connectEvent.Reset();
     m_tcpClient = new TcpClient();
     try
     {
         CommunicationCommon.SetKeepAlive(m_tcpClient.Client, 5000, 1500);
         m_tcpClient.BeginConnect(IPAddress.Parse(strIp), nPort, new AsyncCallback(ConnAsyncCallback), m_tcpClient);
         m_connectEvent.WaitOne(timeOut);
         if (m_tcpClient.Connected)
         {
             InitWorkers();
             return(true);
         }
         else
         {
             m_tcpClient.Close();
             m_bRunning = false;
             return(false);
         }
     }
     catch (System.Exception ex)
     {
         m_strLastErrorMsg = ex.Message;
         return(false);
     }
 }
Esempio n. 2
0
        /// <summary>
        /// 接收数据线程的线程函数
        /// </summary>
        private void RecvProc()
        {
            if (OnConnectionChanged != null)
            {
                OnConnectionChanged(this, true);
            }
            byte[] buffer = new byte[4];
            while (m_bRunning)
            {
                //提取包长
                int dataLen = 0;
                if (CommunicationCommon.ReadAllData(m_netWorkStream, buffer, 4))
                {
                    dataLen = BitConverter.ToInt32(buffer, 0);
                    if (dataLen < 0)
                    {
                        break;//非法数据,关闭客户端
                    }
                }
                else
                {
                    break;
                }

                if (dataLen > 0)
                {
                    buffer = new byte[dataLen];
                    if (CommunicationCommon.ReadAllData(m_netWorkStream, buffer, dataLen))
                    {
                        if (OnReceiveData != null)
                        {
                            OnReceiveData((IPEndPoint)m_ipEndPoint, buffer);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }

            m_netWorkStream.Close();
            m_tcpClient.Close();
            m_bRunning = false;
            if (OnConnectionChanged != null)
            {
                OnConnectionChanged(this, false);
            }
        }