2

我使用 javascript 作为客户端,使用 python 作为服务器。

我需要使用协议缓冲区在它们之间发送/接收。

我的原型看起来像这样:

message CMsgBase
{
    required CMsgHead msghead           = 1;
    optional bytes msgbody              = 2;
}

message CMsgHead
{
    required int32 msgtype                = 1;
    required int32 msgcode                = 2;
}

我在 javascript 中使用 protobuf.js,并使用 XMLHttpRequest 和 POST 方法将数据发送到服务器:

xhr.send(pbMessage.encodeAB());

服务器端可以接收到这个消息并成功解码:

BaseHTTPServer

def do_POST(self):
    pbMessage = self.rfile.read(length) 
    # ...

问题是我无法解码从服务器端接收到的 javascript 端的数据。

这是我从服务器向客户端发送数据的方式:

pbMessageReturn = CMsgBase()
# ......
self.send_response(200)
self.end_headers()

"""Serializes the protocol message to a binary string.

Returns:
  A binary string representation of the message if all of the required
  fields in the message are set (i.e. the message is initialized).
"""

self.wfile.write(pbMessageReturn.SerializeToString())

这是服务器端 print(pbMessageReturn) 的结果:

msghead {
  msgtype: 10006
  msgcode: 1
}
msgbody: "\n\014192.168.1.16"

一切似乎都很好。

以下是我如何在 javascript 中解码来自服务器的消息:

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        var result = xhr.responseText;
        var recvMessage = CMsgBase.decode(result, "utf8");
    }
};

我有一个错误:

protobuf.js:2335 Uncaught Error: Missing at least one required field for Message .CMsgBase: msghead(…)

顺便说一句,如果我尝试发回数据而不对其进行序列化:

self.wfile.write(pbMessageReturn)

我在 javascript 中得到的响应是:

console.log(xhr.responseText);

msghead {
  msgtype: 10006
  msgcode: 1
}
msgbody: "\n\014192.168.1.16"

我真的不确定错误是在服务器端还是在客户端。

任何建议将不胜感激,谢谢:)

4

0 回答 0