简体   繁体   中英

Why does the following trivial protobuf-net code not work correctly?

I am trying to figure out how to work with protobuf-net. The below example is trivial on purpose. It does not reflect a real life application.

Please, observe:

var ms = new MemoryStream();
Serializer.Serialize(ms, 1234);
Serializer.Serialize(ms, 5678);
ms.Position = 0;
var n1 = Serializer.Deserialize<int>(ms);
var n2 = Serializer.Deserialize<int>(ms);
Debug.WriteLine(n1);
Debug.WriteLine(n2);

It outputs:

5678
0

What is wrong?

I am using protobuf-net 2.4.0

As said in the comments, Protobuf doesn't have a concept of 'packets' the way you'd expect. A stream is always fully read on deserialization, previously read values are overriden when they're seen again in the stream. Therefore, writing multiple messages to a single stream won't work the way you do it. Unfortunately, there is no easy fix, you have to implement packet-splitting yourself. One way to do it is to prefix any message by it's length, and split the input accordingly. This works good for bigger message, but your message consists only of a single int which would scale very badly. I'd really suggest not using protobuf at all in this scenario, instead you could take a look at their int-serialization routine (some dynamic-length encoding if I remember correctly) and serialize and deserialize single ints yourself.

You can use BitConverter for converting integers to byte arrays and then sending the arrays to memorystream:

Following link can help:

https://www.c-sharpcorner.com/uploadfile/mahesh/convert-integer-to-byte-array-in-C-Sharp/

then once you have the array of bytearrays, you can do this:

var memoryStream = new MemoryStream();
for(int temp = 0; temp < bytArray.Length; temp++)
  memoryStream.Write(byteArray[temp], 0, byteArray[temp].Length);

Finally, use Protobuff to have memorystream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM