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

后端 未结 2 1006
既然无缘
既然无缘 2021-02-13 02:23

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 an

相关标签:
2条回答
  • 2021-02-13 02:48

    Protobuf 3 introduced a new concept, Any, that handles this. A good description can be found here.

    0 讨论(0)
  • 2021-02-13 02:57

    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.

    0 讨论(0)
提交回复
热议问题