Protobuf-net serialize/deserialize [ProtoBuf.ProtoException: 'Invalid field in source data: 0'] 如何解决?

时间:2021-01-26 10:33:45

标签: .net serialization protobuf-net

我希望你能帮助我,我有这些序列化/反序列化的方法

 public static byte[] ProtoSerialize<T>(T record) where T : class
        {
            if (null == record) return null;

            try
            {
                using (var stream = new MemoryStream())
                {
                    Serializer.Serialize(stream, record);
                    return stream.ToArray();
                }
            }
            catch (Exception ex)
            {
                //_logger.Error(ex, ex.Message);
                // Log error
                throw;
            }
        }

 public static T ProtoDeserialize<T>(byte[] data) where T : class
        {
            if (null == data) return null;

            try
            {
                using (var stream = new MemoryStream(data))
                {
                    return Serializer.Deserialize<T>(stream);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

这是我的模型:

[ProtoContract(SkipConstructor = true)]
    public class DataModel
    {
        [ProtoMember(1)]
        public string Path { get; set; }

        [ProtoMember(2)]
        public byte[] Data { get; set; }
    }

这是如何序列化并发送到 tcp 服务器:

 var dataToSend = new DataModel
  {
    Path = path,
    Data = attachmentContext.LogItemInfo.Attachment
  };
    var tempByte = ProtoSerialize(dataToSend);    
    _client.Connect();
    _client.SendAsync(tempByte);

以及如何反序列化到服务器:

 protected override void OnReceived(byte[] buffer, long offset, long size)
        {
            Console.WriteLine("Packet received");

            var dataModel = ProtoDeserialize<DataModel>(buffer);

            using (var csvFile = File.Create(dataModel.Path))
            {
                //compress, encrypt and save stream to file
                using (var ms = new MemoryStream(dataModel.Data))
                {
                    //compress, encrypt and save stream to file
                    using (var compressedMs = Compress(ms))
                    {
                        compressedMs.Encrypt(csvFile);
                    }
                }
            }

            SendAsync("Received");
        }

在 tcp 服务器中反序列化后出现错误:ProtoBuf.ProtoException: 'Invalid field in source data: 0'

pelase,你能建议如何处理这个问题吗?

0 个答案:

没有答案