public Packet DeserializePacket(IPacketHeader packetHeader, Stream source, out object customErrorData) { customErrorData = null; ET_SCPacketHeader header = packetHeader as ET_SCPacketHeader; if (header == null) { Log.Warning("Packet header is invalid."); return(null); } Packet packet = null; if (header.IsValid) { Type packetType = GetServerToClientPacketType(header.Id); //Log.Debug("~~~~~~~~~~~"+packetType.Name); if (packetType != null && source is MemoryStream) { //packet = (Packet)RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, ReferencePool.Acquire(packetType), packetType, PrefixStyle.Fixed32, 0); object instance = Activator.CreateInstance(packetType); //packet = (Packet)ProtobufHelper.FromStream(packetType, (MemoryStream)source); packet = (Packet)ProtobufHelper.FromStream(instance, (MemoryStream)source); } else { Log.Warning("Can not deserialize packet for packet id '{0}'.", header.Id.ToString()); } } else { Log.Warning("Packet header is invalid."); } ReferencePool.Release(header); return(packet); }
public IPacketHeader DeserializePacketHeader(Stream source, out object customErrorData) { customErrorData = null; ET_SCPacketHeader scHeader = ReferencePool.Acquire <ET_SCPacketHeader>(); MemoryStream memoryStream = source as MemoryStream; if (memoryStream != null) { int packetSize = BitConverter.ToUInt16(memoryStream.GetBuffer(), 0); byte flag = memoryStream.GetBuffer()[ETPackets.ET_MessageFlagIndex]; ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), ETPackets.ET_MessageOpcodeIndex); //这里需要用服务端发过来的packetSize的值减去消息包中flag和opcode的长度, //因为服务端在发送消息时设置的packetSize的值是包含flag和opcode的,而 //客户端在解析包头的时候已经解析了flag和opcode,因此剩余要解析的数据长度要减去3(flag和opcode的总长度是3个字节) scHeader.PacketLength = packetSize - ETPackets.ET_MessageIdentifyLength; scHeader.Flag = flag; scHeader.Id = opcode; return(scHeader); } return(null); }