protobufjs / protobuf.js

Protocol Buffers for JavaScript & TypeScript.
Other
9.91k stars 1.41k forks source link

How to Decode the repeated elements from the ByteBuffer one by one #120

Closed ratheeshr2006 closed 10 years ago

ratheeshr2006 commented 10 years ago

from the server i am encoding the Proto buffer message and I am trying to decode it at the java script .But I was not aware of decoding the repeated elements..please see the below code snippet and respond back the correct way of doing it,

proto file is like below, message AMessage { repeated string str1=1; repeated string str2=2; repeated uint32 score=3; repeated uint32 rank=4; }

server side, it encodes like

AMessage A_msg; A_msg.add_str1("Name1"); A_msg.add_str1("Name 2"); A_msg.add_str2("Mark1"); A_msg.add_str2("Mark2"); A_msg.add_score(78); A_msg.add_score(97); A_msg.add_rank(1); A_msg.add_rank(2);

std::string Multi_param_encoded_string; Multi_param_encoded_string.resize(250); A_msg.SerializeToString(&Multi_param_encoded_string);

then sending through the socket and trying to decode this at the java script end, as like below,

var ProtoBuf_Decode= dcodeIO.ProtoBuf; var builder_Decode = ProtoBuf_Decode.protoFromFile("./amessage.proto"); var Message_Decode = builder_Decode.build("AMessage"); var ByteBuffer = dcodeIO.ByteBuffer; var bb = new ByteBuffer(); bb=ByteBuffer.wrap(responseText).flip(); var Decodemsg = Message_Decode.decode(bb); // Decode

//===here i am blocked,actually I needs to decode the repeated elements one by one from the ByteBuffer and display it.======//

Thanks in advance for your time and support...!!!

dcodeIO commented 10 years ago

First things first: https://github.com/dcodeIO/ProtoBuf.js/wiki/How-to-read-binary-data-in-the-browser-or-under-node.js%3F

Afterwards, you can either wrap the binary data through ByteBuffer.wrap(binaryData) or, if binary is not available and you are using base64 encoding, use ByteBuffer.wrap(base64str, "base64").

Using Message.decode(bb) then will return a message instance with an array for each repeated element containing its values.

ratheeshr2006 commented 10 years ago

Thank you very much for your expert opinion it is working perfectly with base64 encoding and decoding.