/// <summary> /// 接收到消息 /// </summary> void OnReceive(byte[] bytes, int length) { memStream.Seek(0, SeekOrigin.End); memStream.Write(bytes, 0, length); //Reset to beginning memStream.Seek(0, SeekOrigin.Begin); bool isFullMsg = false; int totalLen = 0; //这里要优化,协议HeadStruct已经解析完毕,下次就不需要解析了 memStream.Seek(0, 6); while (RemainingBytes() >= PROTOCOL_HEAD_LENGTH) { totalLen = (int)reader.ReadUInt32(); int messageLen = totalLen & PROTOCOL_HEAD_LENGTH_MASK; ushort mainId = reader.ReadUInt16(); if (RemainingBytes() >= messageLen) { isFullMsg = true; int compressFlag = totalLen & PROTOCOL_HEAD_COMPRESS_MASK; byte[] data = reader.ReadBytes(messageLen); if (0 != compressFlag) { data = decompressor.Decompress(data); } NetworkManagerController.GetInstance().AddEvent(mainId, data); } else { //Back up the position two bytes memStream.Position = memStream.Position - PROTOCOL_HEAD_LENGTH; break; } } //Create a new stream with any leftover bytes if (isFullMsg) { byte[] leftover = reader.ReadBytes((int)RemainingBytes()); memStream.SetLength(0); //Clear memStream.Write(leftover, 0, leftover.Length); } }
void Start() { _networkManagerController = FindObjectOfType <NetworkManagerController>(); }