带有签名的 4 字节 int 的前缀 protobuf 消息

Prefix protobuf message with signed 4 byte int

我正在使用 Websocket API,我将 protobuf 对象发送到该 Websocket。

文档说:

Server uses Big Endian format for binary data. Messages sent back and forth require a signed 4 byte int of the message size, prefixed to the message

因此有效负载应该是一个 4 字节的 int,其中包含消息大小,后跟消息本身。

我这样设置消息:

const message = req.serializeBinary();

我如何为包含消息大小的 signed 4 byte int 添加前缀?

注意:console.log(message) 将以下内容打印到控制台:

jspb.BinaryReader {decoder_: j…b.BinaryDecoder, fieldCursor_: 0, nextField_: -1, nextWireType_: -1, error_: false, …}
decoder_: jspb.BinaryDecoder
bytes_: Uint8Array(78) [0, 0, 0, 74, 152, 182, 75, 75, 242, 233, 64, 4, 49, 48, 53, 57, 242, 233, 64, 35, 77, 101, 115, 115, 97, 103, 101, 32, 108, 101, 110, 103, 116, 104, 32, 114, 101, 99, 101, 105, 118, 101, 100, 32, 105, 115, 32, 105, 110, 118, 97, 108, 105, 100, 46, 194, 233, 64, 19, 82, 105, 116, 104, 109, 105, 99, 32, 83, 121, 115, 116, 101, 109, 32, 73, 110, 102, 111]
cursor_: 78
end_: 78
error_: false
start_: 0
__proto__: Object
error_: false
fieldCursor_: 55
nextField_: 132760
nextWireType_: 2
readCallbacks_: null

我从未使用过 google 的协议缓冲区库,仅使用过 protobuf.js (https://github.com/protobufjs),但我认为我们可以根据您的对象进行工作,因为我们只需要在 message.bytes_

bl = message.bytes_.length;
msg = new Uint8Array(bl+4);
msg.set([(bl&0xff000000)>>24,(bl&0xff0000)>>16,(bl&0xff00)>>8,(bl&0xff)]);
msg.set(message.bytes_,4);
yourwebsocketobject.send(msg); // or maybe msg.buffer?

您可能会得到更好的答案,但这最终可能会奏效。