Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript协议缓冲区解码来自python服务器的数据失败_Javascript_Python_Protocol Buffers_Basehttpserver - Fatal编程技术网

javascript协议缓冲区解码来自python服务器的数据失败

javascript协议缓冲区解码来自python服务器的数据失败,javascript,python,protocol-buffers,basehttpserver,Javascript,Python,Protocol Buffers,Basehttpserver,我使用javascript作为客户端,使用python作为服务器 我需要使用协议缓冲区在它们之间发送/接收 我的原型是这样的: message CMsgBase { required CMsgHead msghead = 1; optional bytes msgbody = 2; } message CMsgHead { required int32 msgtype = 1; requ

我使用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,并使用带有POST方法的XMLHttpRequest将数据发送到服务器:

xhr.send(pbMessage.encodeAB());
服务器端可以接收此消息并成功解码:

BaseHTTPServer 问题是我无法解码从服务器端接收的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())
下面是服务器端打印(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"
我真的不确定错误是在服务器端还是客户端


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

我不是专家,但它看起来像
xhr。responseText
只是消息正文。也许您想要
xhr.response
console.log(xhr.responseText);

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