简体   繁体   English

ProtoBuf-Net进行原始读取

[英]ProtoBuf-Net to do raw read

I want to have a simple piece of code that will iterate through a random stream of protocol buffers, and print out the contents without having an explicit understanding of the structural contents. 我想要一个简单的代码,它将遍历协议缓冲区的随机流,并在不明确了解结构内容的情况下打印出内容。 Something that is equivalent to XmlReader.Read() inside a while loop 在while循环内相当于XmlReader.Read()的东西

using (ProtoBuf.ProtoReader protoReader = 
      new ProtoBuf.ProtoReader(stream1, null, 
            new ProtoBuf.SerializationContext { }))
{
    protoReader.ReadFieldHeader();
    while (protoReader.WireType != ProtoBuf.WireType.None)
    {
       switch (protoReader.WireType)
       {
       case ProtoBuf.WireType.Fixed64:
           Console.WriteLine(protoReader.ReadInt64());
           break;
       case ProtoBuf.WireType.Fixed32:
           Console.WriteLine(protoReader.ReadInt32());
           break;
       case ProtoBuf.WireType.StartGroup:
           Console.WriteLine(protoReader.ReadInt32());
           break;
       default:
           Console.WriteLine(protoReader.WireType);
           break;
       }
    }
}

However I don't know how to advance the protocol buffer to the next element. 但是我不知道如何将协议缓冲区前进到下一个元素。 In my test, it keeps returning "StartGroup" and never advancing. 在我的测试中,它一直返回“ StartGroup”,并且永远不会前进。 How can I advance to the next element in the stream? 如何前进到信息流中的下一个元素?

The ReadFieldHeader() should be inside the loop: ReadFieldHeader()应该在循环内:

while(protoReader.ReadFieldHeader() > 0)
{
    //...
}

Note: if you don't know how to process a given field, there is a .SkipField() method that will correctly read the data - for example: 注意:如果您不知道如何处理给定的字段,则可以使用.SkipField()方法来正确读取数据-例如:

default:
    Console.WriteLine(protoReader.WireType);
    protoReader.SkipField();
    break;

you must read or skip the data exactly once per field-header. 您必须每个字段标题仅读取或跳过一次数据。

In the case of groups and sub-items, you need to use StartSubItem etc: 对于组和子项,您需要使用StartSubItem等:

var tok = ProtoReader.StartSubItem(protoReader);
// an inner while-loop, etc
ProtoReader.EndSubItem(tok);

alternatively: use SkipField() . 或者:使用SkipField()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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