Google protocol buffers, how to handle multiple message types?
Is it possible to get the message type with a serial protocol buffer?
I have this example
option java_outer_classname="ProtoUser";
message User {
required int32 id = 1;
required string name = 2;
required string firstname = 3;
required string lastname = 4;
required string ssn= 5;
}
message Address {
required int32 id = 1;
required string country = 2 [default = "US"];;
optional string state = 3;
optional string city = 4;
optional string street = 5;
optional string zip = 6;
}
In Java, I have this code
Address addr = ProtoUser.Address.newBuilder().setCity("Weston").setCountry("USA").setId(1).setState("FL").setStreet("123 Lakeshore").setZip("90210")
.build();
User user = ProtoUser.User.newBuilder().setId(1).setFirstname("Luis").setLastname("Atencio").setName("luisat").setSsn("555-555-5555").build();
if(....){
FileOutputStream output = new FileOutputStream("out1.ser");
user.writeTo(output);
output.close();
}else{
FileOutputStream output = new FileOutputStream("out1.ser");
addr.writeTo(output);
output.close();
}
Now, can I tell if the file contains an address or a user? What is the general way to handle multiple types of messages? How do I determine what type of message I received?
+3
user2071938
source
to share
2 answers
We cannot determine if the file contains an address or a user. Since there is no type information in the data.
To handle multiple types of messages, you can use metadata, for example:
- File name extension
- HTTP headers
- Specific frame header in the basic frame stream protocol
- ...
+5
Dante
source
to share
Either you:
- Include information whether it is an address or a name at the end of the file (if the files only contain one type at a time)
- Explicitly specify the package type in serialized form, i.e. add a field
required int32 type
and deduce the type from that field. (if both types are included in one file at a time) - Create a custom external message format that explicitly includes this information and wraps the protocol buffer.
Whichever suits you best, if you multiplex them onto the same channel - which you do by selecting the same end of the file - you'll have to demultiplex them again when you get them.
+1
midor
source
to share