基本上,如果我 concat 5 个编码的 protobuf 结果(到一个文件中),我可以得到 2 条消息,但我不能得到 5 条消息。怎么能做到这一点,也许使用encodeDelimited
and decodeDelimited
?或者我必须将它编码为使用AllMessages
并编码一次并解码一次,就像一个数组......这意味着我无法连接结果?repeated
GenericMessage
所以意思是如果我通过网络发送消息,它必须是一个接一个,每个作为一个独立的消息,但不能一起批处理(或连接)并发送一次?
细节:
我正在使用 Node.js 运行以下命令
// awesome-oneof.proto
package awesomepackage;
syntax = "proto3";
message AwesomeMessage {
int32 num = 1;
}
message AwesomeNameMessage {
string name = 1;
}
message GenericMessage {
oneof msg {
AwesomeMessage numberMessage = 1;
AwesomeNameMessage nameMessage = 2;
}
}
写它:
// write.js
const fs = require("fs");
const protobuf = require("protobufjs");
protobuf.load("awesome-oneof.proto", function (err, root) {
if (err) throw err;
const AwesomeMessage = root.lookupType("awesomepackage.GenericMessage");
// const payload = { messageNumber: { a: 150 }};
const payloads = [
{ nameMessage: { name: "Peter" } },
{ numberMessage: { num: 150 } },
{ nameMessage: { name: "Paul" } },
{ nameMessage: { name: "Mary" } },
{ numberMessage: { num: 123 } },
];
payloads.forEach((payload) => {
console.log("payload", payload);
const errMsg = AwesomeMessage.verify(payload);
if (errMsg) throw Error(errMsg);
const message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary
// Encode a message to an Uint8Array (browser) or Buffer (node)
const buffer = AwesomeMessage.encode(message).finish();
console.log(buffer);
fs.writeFileSync("awesome-oneof.dat", buffer, { flag: "as" });
});
});
并阅读它:
// read.js
const fs = require("fs");
const protobuf = require("protobufjs");
protobuf.load("awesome-oneof.proto", function (err, root) {
if (err) throw err;
const AwesomeMessage = root.lookupType("awesomepackage.GenericMessage");
const buffer = fs.readFileSync("awesome-oneof.dat");
console.log(buffer);
let message = AwesomeMessage.decode(buffer);
let object = AwesomeMessage.toObject(message, {
longs: String,
enums: String,
bytes: String,
});
console.log("object", object);
});
结果:
<Buffer 12 07 0a 05 50 65 74 65 72 0a 03 08 96 01 12 06 0a 04 50 61 75
6c 12 06 0a 04 4d 61 72 79 0a 02 08 7b>
object { numberMessage: { num: 123 }, nameMessage: { name: 'Mary' } }
所以我可以取回最新的 2 条消息,但无法取回 5 条。