private void ReceiveCb(IAsyncResult ar) { ClientPeer conn = (ClientPeer)ar.AsyncState; lock (conn) { try { int count = conn.socket.EndReceive(ar); //关闭信号 if (count <= 0) { Console.WriteLine("收到 [" + conn.GetAdress() + "] 断开链接"); conn.Close(); return; } conn.buffCount += count; ProcessData(conn); //继续接收 conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn); } catch (Exception e) { Console.WriteLine("收到 [" + conn.GetAdress() + "] 断开链接 " + e.Message); conn.Close(); } } }
//心跳 public void HeartBeat() { //Console.WriteLine ("[主定时器执行]"); long timeNow = Sys.GetTimeStamp(); for (int i = 0; i < conns.Length; i++) { ClientPeer conn = conns[i]; if (conn == null) { continue; } if (!conn.isUse) { continue; } if (conn.lastTickTime < timeNow - heartBeatTime) { Console.WriteLine("[心跳引起断开连接]" + conn.GetAdress()); lock (conn) conn.Close(); } } }
//关闭 public void Close() { for (int i = 0; i < conns.Length; i++) { ClientPeer conn = conns[i]; if (conn == null) { continue; } if (!conn.isUse) { continue; } lock (conn) { conn.Close(); } } }