【问题标题】:Prefix protobuf message with signed 4 byte int带有签名的 4 字节 int 的 protobuf 消息前缀
【发布时间】:2021-04-21 01:30:30
【问题描述】:

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

文档说:

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

因此有效负载应该是一个 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

【问题讨论】:

    标签: javascript websocket protocol-buffers protobuf.js


    【解决方案1】:

    我从未使用过 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?
    

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

    【讨论】:

    • 你确定msg.set 行是正确的吗?当我隔离它并将 bl 的值硬编码为 4 时,字节全为零......就像我尝试使用真实消息长度时一样。
    • 哪一行不适合你,第一个 msg.set 还是第二个?对我来说,这一切都适用于 node 和 firefox,你在哪个环境中?
    • 这是一个示例,其中在隔离前 4 个字节的代码时,87 被编码为 [0, 0, 0, 7]pastebin.com/1ERyYaPK
    • 哎呀!我很抱歉。我错误地使用了位掩码,0xf 而不是 0xff。我以前没有看到这个,因为我测试的值低于 16。谢谢你告诉我。现在已经修复了。
    • 做到了。谢谢!
    猜你喜欢
    • 2012-07-23
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2013-07-09
    • 1970-01-01
    相关资源
    最近更新 更多