private void OnReceivedDatas(ClientSocket clientSocket) { ByteArray readBuffer = clientSocket.ReadBuffer; if (readBuffer.Length <= 4 || readBuffer.ReadIndex < 0) { return; } int readIdx = readBuffer.ReadIndex; byte[] bytes = readBuffer.Bytes; int bodyLength = BitConverter.ToInt32(bytes, readIdx); //判断接收到的信息长度是否小于包体长度+包体头长度,如果小于,代表我们的信息不全,大于代表信息全了(有可能有粘包存在) if (readBuffer.Length < bodyLength + 4) { return; } readBuffer.ReadIndex += 4; //解析协议名 int nameCount = 0; ProtocolEnum proto = ProtocolEnum.None; try { proto = _messageParser.DecodeName(readBuffer.Bytes, readBuffer.ReadIndex, out nameCount); } catch (Exception ex) { Debug.LogError($"解析协议名出错:{ex}"); CloseClient(clientSocket); return; } if (proto == ProtocolEnum.None) { Debug.LogError($"OnReceiveData MsgBase.DecodeName fail.Proto type is Null!"); CloseClient(clientSocket); return; } readBuffer.ReadIndex += nameCount; //解析协议体 int bodyCount = bodyLength - nameCount; MessageBase messageBase = null; try { messageBase = _messageParser.DecodeContent(proto, readBuffer.Bytes, readBuffer.ReadIndex, bodyCount); if (messageBase == null) { Debug.LogError($"{proto}协议内容解析出错!!!!!"); CloseClient(clientSocket); return; } } catch (Exception ex) { Debug.LogError($"接收数据协议内容解析错误:{ex}"); CloseClient(clientSocket); return; } readBuffer.ReadIndex += bodyCount; readBuffer.CheckMoveBytes(); if (!_protocolHandles.ContainsKey(proto)) { Debug.LogError($"没有协议的处理方法:{proto}"); CloseClient(clientSocket); return; } _protocolHandles[proto]?.Invoke(clientSocket, messageBase); if (readBuffer.Length > 4) { OnReceivedDatas(clientSocket); } }
/// <summary> /// 对数据进行处理 /// </summary> void OnReceiveData() { if (_readBuffer.Length <= 4 || _readBuffer.ReadIndex < 0) { return; } int readIdx = _readBuffer.ReadIndex; byte[] bytes = _readBuffer.Bytes; int bodyLength = BitConverter.ToInt32(bytes, readIdx); //读取协议长度之后进行判断,如果消息长度小于读出来的消息长度,证明是没有一条完整的数据 if (_readBuffer.Length < bodyLength + 4) { return; } _readBuffer.ReadIndex += 4; int nameCount = 0; ProtocolEnum protocol = _messageParser.DecodeName(_readBuffer.Bytes, _readBuffer.ReadIndex, out nameCount); if (protocol == ProtocolEnum.None) { Debug.LogError("OnReceiveData MsgBase.DecodeName fail"); Close(); return; } _readBuffer.ReadIndex += nameCount; //解析协议体 int bodyCount = bodyLength - nameCount; try { MessageBase msgBase = _messageParser.DecodeContent(protocol, _readBuffer.Bytes, _readBuffer.ReadIndex, bodyCount); if (msgBase == null) { Debug.LogError("接受数据协议内容解析出错"); Close(); return; } _readBuffer.ReadIndex += bodyCount; _readBuffer.CheckMoveBytes(); //协议具体的操作 lock (_messageList) { _messageList.Add(msgBase); } _messageCount++; //处理粘包 if (_readBuffer.Length > 4) { OnReceiveData(); } } catch (Exception ex) { Debug.LogError("Socket OnReceiveData error:" + ex.ToString()); Close(); } }