用于了解正在发送的 protobuf 消息类型的 API
知道正在发送的 protobuf 消息类型的 API 是什么?
例如,我使用以下方法来获取 SendNameMessage 对象。
SendNameMessage sendNameObj = Serializer.DeserializeWithLengthPrefix< SendNameMessage>(流, PrefixStyle.Fixed32);
监听者如何知道正在发送什么类型的消息?
以下是我的SendNameMessage 类:
[ProtoContract]
class SendNameMessage
{
[ProtoMember(1)]
public string sendName { get; set; }
[ProtoMember(2)]
public int sendId { get; set; }
}
我如何知道正在发送的消息是sendName 还是sendId?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
protobuf(在任何实现下)只是序列化 API。当在线通话时,默认是两端已经同意数据是什么。为了发送不同类型的消息,有一些选项:
Base128
前缀样式,您可以包含与消息一起发送的字段编号(默认为1
,但重载方法允许您指定这一点)。然后,您可以通过Serializer.NonGeneric.TryDeserializeWithLengthPrefix
对其进行反序列化,其中包含一个委托参数,用于从字段编号执行类型解析。编辑后...您提到
sendId
和sendName
,但消息是SendNameMessage
。它总是是该消息中的所有内容(默认值除外)。可能两者皆有。两者都可能不是。因此,在那种场景中,您只需反序列化它并检查.sendName
和.sendId
。这里的另一个常见选项是添加一个鉴别器,也许只是一个枚举:
并在消息中包含那个:
现在您有一个明确表达您消息类型含义的方式。
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:
Base128
prefix-style, you can include a field number that is sent with the message (it defaults to1
, but an overloaded method allows you to specify this). You would then deserialize this viaSerializer.NonGeneric.TryDeserializeWithLengthPrefix
which includes a delegate parameter to perform type resolution from the field number.After the edit... you mention
sendId
andsendName
, but the message isSendNameMessage
. 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:
and include that on the message:
Now you have an explicit way of expressing your meaning of message-type.