1

我正在使用向其发送 protobuf 对象的 Websocket API。

文档说:

服务器对二进制数据使用 Big Endian 格式。来回发送的消息需要一个有符号的 4 字节 int 的消息大小,作为消息的前缀

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

我这样设置消息:

const message = req.serializeBinary();

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

注意: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
4

1 回答 1

1

我从未使用过谷歌的协议缓冲区库,只有 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?

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

于 2021-01-16T04:18:56.550 回答