private void OnRecveTimeOut_Tick(object sender, EventArgs e) { if (!Working) { return; } ClarifyInfo($"已超过[{ReceiveTimeOut.ToString()}]没有收到数据,断开连接。", 1); Disconnect(); }
/// <summary> /// 数据接收线程 /// 以轮询方式接收字节流。 /// </summary> private void ReceiveThread() { try { ClarifyInfo(string.Format("连接[{0}:{1}]的工作线程开始工作……", m_RemoteHost, m_RemotePort), 1); // 通讯协议进入预备状态 if (_Protocol != null) { _Protocol.Start(); } byte[] aByteBuffer = new byte[ReceiveBufferLength]; // 接收数据,将收到的数据片通知通讯协议处理。 Stopwatch aReceiveStopwatch = new Stopwatch(); Stopwatch aHeartBeatStopwatch = new Stopwatch(); aReceiveStopwatch.Start(); aHeartBeatStopwatch.Start(); while (Working) { try { if (_NetworkStream.DataAvailable) { // 以字节块为单位接收数据 int aReadBytesCount = _NetworkStream.Read(aByteBuffer, 0, aByteBuffer.Length); if (aReadBytesCount > 0) { byte[] aCopy = new byte[aReadBytesCount]; System.Array.Copy(aByteBuffer, aCopy, aReadBytesCount); // 通知收到数据 ClarifyBytesReceived(aCopy); // 协议实例分析数据 if (_Protocol != null) { _Protocol.ClarifyReceivedBytes(this, aCopy); } } aReceiveStopwatch = Stopwatch.StartNew(); } else { // 没有数据要接收时,暂时交出控制权,以减少对系统响应的影响。 System.Threading.Thread.Sleep(IdleInterval); if (ReceiveTimeOut > TimeSpan.Zero && aReceiveStopwatch.Elapsed > ReceiveTimeOut) { ClarifyInfo($"已超过[{ReceiveTimeOut.ToString()}]没有收到数据,断开连接。", 1); Disconnect(); break; } else { // 发送心跳,检查连接状态 try { byte[] aBytes = _Protocol == null ? new byte[0] : _Protocol.HeartBeat(); if (aBytes.Length == 0 || aHeartBeatStopwatch.Elapsed >= HeartBeatInterval) { _TcpClient.Client.Send(aBytes); aHeartBeatStopwatch = Stopwatch.StartNew(); } } catch (Exception ex) { ClarifyInfo(string.Format("连接[{0}:{1}]的工作线程发生错误:{2},断开连接。", m_RemoteHost, m_RemotePort, ex.Message), 0); Disconnect(); break; } } } } catch (System.Threading.ThreadAbortException) { throw; } catch (Exception ex) { ClarifyInfo(ex.Message, 0); } } ClarifyInfo(string.Format("连接[{0}:{1}]的工作线程停止。", m_RemoteHost, m_RemotePort), 1); } catch (System.Threading.ThreadAbortException) { // 调用ResetAbort来阻止再次引发此异常,令线程正常结束。 ClarifyInfo(string.Format("连接[{0}:{1}]的工作线程被中止……", m_RemoteHost, m_RemotePort), 0); System.Threading.Thread.ResetAbort(); } catch (Exception ex) { ClarifyInfo(string.Format("连接[{0}:{1}]的工作线程发生错误:{2}", m_RemoteHost, m_RemotePort, ex.Message), 0); ClarifyInfo(ex.StackTrace, 4); } }