private void RecvExec() { if (m_client == null) { return; } if (ConnectState.Connected != m_connectState) { return; } int len = m_client.Client.Receive(tmpRecvBuf); if (len > 0) { netRecvBuf.AddBuffer(tmpRecvBuf, len); NetRecvData tmpRecvData = new NetRecvData(); // 一次取一条,把receive的buff取完为止 lock (msgQueue) { while (netRecvBuf.GetOneMsg(ref tmpRecvData)) { if (tmpRecvData._msgId > 0) { //Debug.Log("Enqueue ++ ==>> " + tmpRecvData._msgId); msgQueue.Enqueue(tmpRecvData); } } } } }
IEnumerator DealWithMessage() { lock (msgQueue) { while (msgQueue.Count > 0) { NetRecvData recvData = msgQueue.Dequeue(); int msgId = recvData._msgId; if (msgId <= 0) { Debug.Log("网络数据不正常,停卡处理此协议"); yield break; } try { byte[] bytes = recvData._data; LuaByteBuffer buff = new LuaByteBuffer(bytes); CallMethod(OnMessage, msgId, buff); if (msgId == 1201) { lostHeartTimes = 0; //重置心跳网络检查 } buff = null; } catch (Exception e) { OnDisconnected(DisType.Exception, "消息报错: [msgId]" + msgId + " >> " + e.Message + "|" + e.StackTrace); } yield return(null); } } yield break; }
public bool GetOneMsg(ref NetRecvData recvData) { if (_buffLen <= 0) { UpdateLen(); } if (_buffLen > 0 && _buffLen <= _curPos) { recvData._msgId = _msgId; recvData._data = new byte[_dataLen]; Array.Copy(_buff, NetConst.MSG_HEAD_LEN, recvData._data, 0, _dataLen); _curPos -= _buffLen; byte[] newBuf = new byte[_curPos > NetConst.TMP_BUF_SIZE ? _curPos : NetConst.TMP_BUF_SIZE]; Array.Copy(_buff, _buffLen, newBuf, 0, _curPos); _buff = newBuf; newBuf = null; _buffLen = 0; _dataLen = 0; _msgId = 0; return(true); } return(false); }