首页 > 解决方案 > 通过 protobuf 在服务器(node.js)和客户端(python/node.js)之间交换消息

问题描述

我正在研究 protobuf 协议,当服务器(节点 js)+ 客户端(python)不想交换 msgs 时遇到了问题。在服务器(节点 js)+ 客户端(节点 js)之间没问题。两个客户端使用相同的服务器。我发现 python 和 node js 客户端之间存在差异,序列化后 msg 字节数组不同,这可能是问题的原因。但是我的知识不足以解决这个问题。可能有人看到问题了吗?

客户端js

const instance = new Product.Id().setValue(12345);
let message = instance.serializeBinary();
console.log(message); //Uint8Array(3) [ 8, 185, 96 ]
let response = await fetch('http://localhost:3008/api/getById', {
    method: 'POST',
    body: message,
    headers: {'Content-Type': 'application/protobuf'}
});

客户端py

instance.id.value = 12345
byte = instance.SerializeToString()
print(byte) #b'\n\x03\x08\xb9`'
response = requests.post(url = "http://localhost:3008/api/getById", headers={'Content-Type': 'application/protobuf'}, data=byte)

服务器接收:客户端 js:08 b9 60 客户端 py:0a 03 08 b9 60

我还发现了这个主题:在 python 和 nodejs 之间使用 protobuf 的序列化问题如果是编码问题,如何正确编码?

标签: pythonnode.jsprotocol-buffers

解决方案


检测到问题,而不是:

instance.id.value = 12345
byte = instance.SerializeToString()

应该:

instance.id.value = 12345
byte = instance.id.SerializeToString()

推荐阅读