private void ReceiveCallBack(IAsyncResult ar) { try { Socket socket = (Socket)ar.AsyncState; int length = socket.EndReceive(ar); NetBufferReader netBufferReader = new NetBufferReader(recvBuffer); string msg = netBufferReader.GetString(); Debug.Log(msg); if (msg == "pong") { pingValue = NetTimer.GetTimeStamp() - lastPingTime; } else { if (receivedSucceed != null) { receivedSucceed(msg); } } //处理消息 socket.BeginReceive(recvBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, socket); } catch (Exception e) { Debug.Log(e.ToString()); DisConnect(); } }
/// <summary> /// 处理心跳 /// </summary> public void StartHeartCheck(Action <ClientSocket> errorHandle) { lastPingTime = NetTimer.GetTimeStamp(); while (true) { long nowT = NetTimer.GetTimeStamp(); if (nowT - lastPingTime > aliveTime) { //处理客户端断线 Disconnect(errorHandle); } } }
private void HeartSend() { SendMsg("ping"); lastPingTime = NetTimer.GetTimeStamp(); while (true) { if (clientSocket.Connected) { if (NetTimer.GetTimeStamp() - lastPingTime >= pingInterval) { SendMsg("ping"); lastPingTime = NetTimer.GetTimeStamp(); } } } }
private void startBroadFrame() { while (true) { //Console.WriteLine(NetTimer.GetTimeStamp()); //距离上次广播满足一帧的间隔 long nowT = NetTimer.GetTimeStamp(); if (nowT - lastFrame >= frameInterval) { //重新广播 Console.WriteLine("开始广播关键帧"); MessageHandle.Ins.BroadFrameMsg(); lastFrame = NetTimer.GetTimeStamp(); } } }
private void RecvMsgHandle(string msg) { switch (msg) { case "ping": lastPingTime = NetTimer.GetTimeStamp(); Console.WriteLine("【心跳{0}】ID {1}:{2}", socket.RemoteEndPoint.ToString(), id, msg); SendBytes(string.Format("pong")); break; default: Console.WriteLine("【收 到{0}】ID {1}:{2}", socket.RemoteEndPoint.ToString(), id, msg); //SendBytes(string.Format("服务器反馈:收到来自ID为{0}的消息_{1}", id, msg)); //将服务器收到的消息缓存起来 MessageHandle.Ins.StoreFrameMsg(msg); break; } }