public static Packet Deserialize(Session session, MemoryStream source, out object customErrorData) { customErrorData = null; long begin = source.Position; byte[] buffer = new byte[4]; source.Read(buffer, 0, sizeof(int)); int id = ConverterUtility.GetInt32(buffer); Packet packet = ProtoRegister.GetPacket(id); packet.DeSerialize(source); return(packet); }
public override void LoadData(byte[] bytes) { _dataList.Clear(); int pos = 0; int dataCount = ConverterUtility.GetInt32(bytes, pos); pos += Marshal.SizeOf(pos);//int大小; for (int i = 0; i < dataCount; i++) { T data = Activator.CreateInstance <T>(); data.Decode(bytes, ref pos); _dataList.Add(data); } }
protected static void ReadInt32(ref byte[] byteArr, ref int byteOffset, out int outputValue) { outputValue = ConverterUtility.GetInt32(byteArr, byteOffset); byteOffset += ConverterUtility.INT_LENGTH; }
private bool Process() { if (_receiver.ReceivedLength != _receiver.Length) { throw new Exception(string.Format("Receive length '{0}' is not equal to length '{1}'.", _receiver.ReceivedLength.ToString(), _receiver.Length.ToString())); } if (_receiver.Length < _defaultPacketLength) { throw new Exception(string.Format("Length '{0}' is smaller than length header.", _receiver.Length.ToString())); } if (_receiver.Length == _defaultPacketLength) { int packetLength = ConverterUtility.GetInt32(_receiver.GetBuffer()); if (packetLength <= 0) { string errorMessage = string.Format("Packet length '{0}' is invalid.", packetLength.ToString()); if (ErrorHandler != null) { ErrorHandler(this, SessionErrorCode.HeaderError, errorMessage); return(false); } throw new Exception(errorMessage); } _receiver.Length += packetLength; if (_receiver.Length > _receiver.BufferSize) { string errorMessage = string.Format("Length '{0}' is larger than buffer size '{1}'.", _receiver.Length.ToString(), _receiver.BufferSize.ToString()); if (ErrorHandler != null) { ErrorHandler(this, SessionErrorCode.OutOfRangeError, errorMessage);//未接收完成,继续; return(false); } throw new Exception(errorMessage); } return(true); } Packet packet = null; try { int packetLength = _receiver.Length - _defaultPacketLength; object customErrorData = null; using (MemoryStream memoryStream = new MemoryStream(_receiver.GetBuffer(), _defaultPacketLength, packetLength, false)) { lock (thisLock) { packet = SessionUtil.Deserialize(this, memoryStream, out customErrorData); } } _receiver.Reset(_defaultPacketLength); if (packet == null) { if (CustomErrorHandler != null) { CustomErrorHandler(this, customErrorData); } } else { if (ReceiveHandler != null) { ReceiveHandler(this, packet); } } } catch (Exception exception) { _active = false; if (ErrorHandler != null) { ErrorHandler(this, SessionErrorCode.DeserializeError, exception.ToString()); return(false); } throw; } return(true); }