开发者

How do i get the length number using PrefixStyle with ProtoBuf-net?

in the example below how do i get the length number using PrefixStyle wit开发者_开发知识库h ProtoBuf-net?

and what's the difference between PrefixStyle.Base128 and PrefixStyle.Fixed32?

Thanks!

            PerfTest clone;
            using (MemoryStream ms = new MemoryStream())
            {
                Serializer.SerializeWithLengthPrefix(ms, obj,PrefixStyle.Base128);
                byte[] raw = ms.ToArray();
                ms.Position = 0;
                clone = Serializer.DeserializeWithLengthPrefix<PerfTest>(ms,PrefixStyle.Base128);

            }

Edit: Using the code below the byte array has a length of 22. Why does TryReadLengthPrefix return 21? Surely is should return 22?

           PerfTest clone;
            using (MemoryStream ms = new MemoryStream())
            {
                Serializer.SerializeWithLengthPrefix(ms, obj,PrefixStyle.Base128);
                byte[] raw = ms.ToArray();
                ms.Position = 0;

                int bArrayLen = ms.ToArray().Length; //returns 22

                int len;// set to 21. Why not 22?
                Serializer.TryReadLengthPrefix(ms, PrefixStyle.Base128,out len);

                clone = Serializer.DeserializeWithLengthPrefix<PerfTest>(ms,PrefixStyle.Fixed32);

            }


Fixed32 always uses 4 bytes for the length prefix - this seems to be not uncommon for people packing messages manually (indeed, I even had to add different-endian versions at some point, due to repeat requests).

The preference though should be Base128, which uses "varint" encoding, so small numbers take less space to encode. Additionally, this prefix style can be used to make a sequence of objects wire-compatible with a single object with a repeated field, which has some useful applications.

Re getting the length; if you are using DeserializeWithLenghPrefix or DeserializeItems you shouldnt need to - it handles it internally. But if you need this, look at Serializer.TryReadLengthPrefix.

To clarify: the purpose of the *WithLengthPrefix methods is to allow separation of different objects/messages in a single stream - most commonly: network sockets. This is necessary because the protocol itself otherwise assumes an entire stream is a single message, so would keep trying to read until the stream/socket was closed.

Re the 22 vs 21 bytes; that is because the length prefix itself takes some length :) actually if the array is 22 I'm a little surprised the payload isn't 20 - I byte field headed (to make the composed stream itself a valid protobuf stream), 1 byte length, and 20 bytes payload. I'm on a mobile at the moment, so I can't run the sample to investigate; it is possible to omit the field-header (optionally), though - so it could be 1 byte length, 21 bytes payload. I'll look later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜