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を使用しており、POSTメソッドでXMLHttpRequestを使用してサーバーにデータを送信しています:

xhr.send(pbMessage.encodeAB());

サーバー側はこのメッセージを受信し、正常にデコードできます。

ベースHTTPサーバー

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