tags:

views:

43

answers:

1

What is the API to know the kind of protobuf Message is being sent?

For example I use the following to get the SendNameMessage object.

SendNameMessage sendNameObj = Serializer.DeserializeWithLengthPrefix< SendNameMessage>(stream, PrefixStyle.Fixed32);

How does a listener know what kind of message is being sent?

The following is my SendNameMessage class:

[ProtoContract]
class SendNameMessage
{
    [ProtoMember(1)]
    public string sendName { get; set; }

    [ProtoMember(2)]
    public int sendId { get; set; }
}

How do I know if the message being sent is sendName or sendId?

+1  A: 

protobuf (under any implementation) is just the serialization API. When talking on the wire, the default is that both ends already agree what the data is. For sending different types of messages, a few options present themselves:

  1. have a wrapper object that simply has child objects to represent different message types. With protobuf-net specifically you can also map this directly to inheritance (since protobuf-net maps inheritance to encapsulation)
  2. use a message header - some kind of data before your message that identifies this. In particular, if using the Base128 prefix-style, you can include a field number that is sent with the message (it defaults to 1, but an overloaded method allows you to specify this). You would then deserialize this via Serializer.NonGeneric.TryDeserializeWithLengthPrefix which includes a delegate parameter to perform type resolution from the field number.

After the edit... you mention sendId and sendName, but the message is SendNameMessage. It will always be everything (except defaults) in that message. It could be both. It could be neither. So in that scenario, you would just deserialize it and check .sendName and .sendId.

Another common option here is to add a discriminator, perhaps simply an enum:

enum MesageType {
    Error = 0,
    Name = 1,
    Id = 2
}

and include that on the message:

[ProtoMember(10)]
public MessageType MessageType {get;set;}

Now you have an explicit way of expressing your meaning of message-type.

Marc Gravell
Marc I made a mistake in my question. I made changes to my question.
sonu
I thought there was an easier way of doing this than checking each member as I have at least 10 proto members.
sonu
@sonu - but that it just how *you* are choosing to use it. As far as the system is concerned `SendNameMessage` is the message. The fact that you are only sending individual properties is up to you...
Marc Gravell