协议缓冲区从原始消息中检测类型 [英] Protocol buffers detect type from raw message

查看:41
本文介绍了协议缓冲区从原始消息中检测类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检测原始协议缓冲区消息的类型(以字节[]为单位)

Is it possible to detect the type of a raw protocol buffer message (in byte[])

我遇到一种情况,端点可以接收不同的消息,并且我必须能够检测类型,然后才能对它进行反序列化.

I have a situation where an endpoint can receive different messages and I need to be able to detect the type before I can deserialize it.

我正在使用protobuf-net

I am using protobuf-net

推荐答案

您无法孤立地检测类型,因为protobuf规范并未为此添加任何数据;但是,有多种方法可以使此操作变得容易,具体取决于上下文:

You can't detect the type in isolation, since the protobuf spec doesn't add any data to the stream for this; however, there are a number of ways of making this easy, depending on the context:

  • 联合类型(如乔恩·乔恩提到的)涵盖了多种情况
  • 继承(特定于protobuf-net)可以是通用的-您可以具有基本消息类型,以及任意数量的具体消息类型
  • 您可以使用前缀指示传入的类型

在原始TCP流的情况下,最后一种方法实际上非常有价值;在线与联合类型相同,但实现方式不同;通过预先确定1 = Foo,2 = Bar等(与联合类型方法完全相同),可以使用 SerializeWithLengthPrefix 进行写(将1/2/etc指定为字段号),以及要读取的非泛型 TryDeserializeWithLengthPrefix (位于v1 API中的Serializer.NonGeneric下,或v2 API中的TypeModel下),则可以提供用于解析数字的类型图返回类型,从而反序列化正确的类型.并优先考虑为什么这对TCP流有用?"这一问题.-因为:在进行中的TCP流中,您仍然使用 WithLengthPrefix 方法无论如何,以避免过度读取该流;因此您最好免费获取类型标识符!

the last approach is actually very valuable in the case of raw TCP streams; this is on the wire identical to the union type, but with a different implementation; by deciding in advance that 1=Foo, 2=Bar etc (exactly as you do for the union type approach), you can use SerializeWithLengthPrefix to write (specifying the 1/2/etc as the field number), and the non-generic TryDeserializeWithLengthPrefix to read (this is under Serializer.NonGeneric in the v1 API, or on the TypeModel in the v2 API), you can provide a type-map that resolves the numbers back to types, and hence deserialize the correct type. And to pre-empt the question "why is this useful with TCP streams?" - because: in an ongoing TCP stream you need to use the WithLengthPrefix methods anyway, to avoid over-reading the stream; so you might as well get the type identifier for free!

摘要:

  • 联合类型:易于实现;唯一的缺点是然后必须检查哪些属性为非空
  • 继承性:易于实现;可以使用多态或判别器来处理现在如何?"
  • 类型前缀:实现起来比较麻烦,但具有更大的灵活性,并且TCP流的开销为零

这篇关于协议缓冲区从原始消息中检测类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆