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(); } } }
//Accept回调 private void AcceptCb(IAsyncResult ar) { try { Socket socket = listenfd.EndAccept(ar); int index = NewIndex(); if (index < 0) { socket.Close(); Console.Write("[警告]链接已满"); } else { ClientPeer conn = conns[index]; conn.Init(socket); string adr = conn.GetAdress(); Console.WriteLine("客户端连接 [" + adr + "] conn池ID:" + index); conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn); } listenfd.BeginAccept(AcceptCb, null); } catch (Exception e) { Console.WriteLine("AcceptCb失败:" + e.Message); } }
//发送 public void Send(ClientPeer conn, ProtocolBase protocol) { byte[] bytes = protocol.Encode(); byte[] length = BitConverter.GetBytes(bytes.Length); byte[] sendbuff = length.Concat(bytes).ToArray(); try { conn.socket.BeginSend(sendbuff, 0, sendbuff.Length, SocketFlags.None, null, null); } catch (Exception e) { Console.WriteLine("[发送消息]" + conn.GetAdress() + " : " + e.Message); } }