解码 protobuf.js 中的一组消息

Decode an array of messages in protobuf.js

在我们的 node.js 应用程序中,我们需要反序列化我们知道包含多个对象的缓冲区。 protobuf-net 是这样完成的:

var stream = new MemoryStream(byteData);
List<Schema.Object> objects = ProtoBuf.Serializer.Deserialize<List<Schema.Object>>(stream);

我现在正尝试对 protobuf.js 做同样的事情。我还没有找到创建模型对象数组的示例,只有一个模型对象,如下所示:

const Object = root.lookupType('model.Object');
const message = Object.decode(byteData); //this creates one object but the buffer contains multiple objects

如何使用 protobuf.js 创建对象数组而不是单个对象?

以下是数据的序列化方式:

try
    {
        using (var stream = new MemoryStream())
        {
            ProtoBuf.Serializer.Serialize(stream, objects);
            Stream.Position = 0;

            // Return the serialized byte array.
            return stream.ToArray();
        }
    }
    finally {}
}

找到解决办法。您可以用包含重复条目的另一条消息包装对象。然后当它被解码时,它将是一个对象数组。

在 .proto 文件中:

message ObjectCollection {
  repeated Object objects = 1;
}