android.developer android.developer - 1 year ago 71
Java Question

How to determine message type in protobuf so that I can use that type.parsefrom(byte[ ])

I am trying to send protobuf data from cpp side to java side.

I have multiple message types defined in .proto

On Cpp side, I have enums for every message type and I am adding it to the buf output as follows:

uint8_t* __temp = (uint8_t*)(buf);
*__temp++ = (type) >> 8;
*__temp = (type) & 0x00FF;

How do I get this 'type' that I have added to the buf, so that I can achieve something like

MessageType parseFrom(byte[] data);

Answer Source

It is not clear what is the exact requirement. But I assume you are trying to send different types of messages and the the receiver should be able to parse the correct object out of the received bytes. This can be done as shown in the example below:

message Message1 {
   required string a = 1;
   required string b = 2;

message Message2 {
   required int64 id = 1;
   required string data = 2;

message WrapperMessage {
    required int64 commonField = 1;
    oneof msg {
        Message1 m1 = 2;
        Message2 m2 = 3;

Basically, always WrapperMessage object is sent over the wire which wraps a Message1 or Message2 object. Then on the receiving side we may parse the WrapperMessage object first and then use HasField method to check if m1 or m2 fields is present in the wrapped object and then parse the Message1 or Message2 object out of it.

"oneof" feature may not be available on older version of protobuf compiler.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download