2

I am using javascript as client and a python as server.

I need to send/receive in between them using protocol buffer.

My proto looks like this :

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

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

I am using protobuf.js in javascript and is sending the data to server using XMLHttpRequest with a POST method :

xhr.send(pbMessage.encodeAB());

The server side can receive this message and decode it successfully:

BaseHTTPServer

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

The problem is that I can not decode the data in javascript side received from the server side.

Here is how I send the data to client from server :

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())

And here is the result of print(pbMessageReturn) in server side :

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

Everything seem s to be fine.

And here is how I decode the message from server in javascript:

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

And I am having an error:

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

BTW, if I try to send the back the data without serialize it:

self.wfile.write(pbMessageReturn)

The response I get in javascript is :

console.log(xhr.responseText);

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

I am really not sure if the error is in the server side or the client side.

Any advice will be appreciated, thanks :)

1
  • I'm not an expert, but it looks like xhr.responseText is just the message body. Perhaps you want xhr.response instead? Commented Dec 7, 2016 at 8:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.