0

I am new to protocol buffers and I am having issues with multiple messages using Any data. I am not sure if I am using it correctly.

I have the following in message.proto

import "google/protobuf/any.proto";

message config {
    string ip = 1;
    string username = 2;
    string serialnumber = 3;
};

message userdata {
    string username = 1;
};

message ServerMessage {
    config = 1;
    userdata = 2;
    google.protobuf.Any data = 3;
};

I am trying to serialize and send the data like below

ServerMessage server_msg;
google::protobuf::Any any;
server_msg.mutable_userdata()->set_username("test");

any.PackFrom(server_msg);
boost::asio::streambuf sbuf;
ostream serialized(&sbuf);
any.SerializeToOstream(&serialized);

On the receiving side, I try to deserialize like below

userdata msg;
google::protobuf::Any any;

any.ParseFromArray(message.data(), message.size()); 

if (any.Is<userdata>()) {
     std::cout<<"It is a userdata mesage"<<std::endl;
}
if (any.Is<config>()) {
     std::cout<<"it is a config message"<<std::endl;
}

if (any.UnpackTo(&msg)) {
    std::cout<<msg.username()<<std::endl;
} else {
     std::cout<<"could not unpack"<<std::endl;
}

The packing doesn't complain. But it is not able to unpack or determine the message type.

Am I packing it wrong? I really appreciate your help with this!

Raju Ahmed
  • 1,282
  • 5
  • 15
  • 24
Gatothgaj
  • 1,633
  • 2
  • 16
  • 27

1 Answers1

1

I am not an expert on Protobuf, but I think the problem is that you are packing a ServerMessage and unpacking a userdata.

You should unpack a ServerMessage and then access the userdata() member.

adiego73
  • 189
  • 1
  • 3
  • 13