我使用Cap'n proto来发送和检索多个客户端和我的websocket服务器之间的消息。
由于我只有一个websocket通道来发送和接收数据,并且可以发送各种类型的消息,所以我需要一种方法来区分尝试对它进行解码。
如何在Cap'n proto中正确完成?
我认为这个问题是语言不可知的,但如果需要一种语言,我需要在Rust和Go,Javascript等客户端中使用我的服务器,因此可以使用适用于所有这些语言的解决方案。
I'm using Cap'n proto to send and retrieve messages between multiple clients and my websocket server.
Since I have only one websocket channel to send and receive data and various type of messages can be sent, I need a way to distinguish between then when trying to decode it.
How can this be done correctly in Cap'n proto?
I think this question is language agnostic, but if a language is needed, I have my server in Rust and clients in Rust, Go and Javascript, so a solution that works in all these languages would be much appreciated.
最满意答案
最好的办法是创建一个外部结构,它是所有可能类型的联合。 例如,如果您有类型Foo , Bar和Baz ,请定义类型如下:
struct Outer { union { foo @0 :Foo; bar @1 :Bar; baz @2 :Baz; } }如何访问联合取决于语言,但通常有一个which()方法返回一个枚举值,指定填充哪个字段,然后对嵌套结构使用常规getter方法。
请注意,两端必须使用此外部类型。 您不能使用Foo的根类型序列化消息,然后将其解析为Outer消息 - 消息必须使用Outer类型创建。 一般来说,没有办法根据字节单独区分不同的Cap'n Proto类型。
The best thing to do is create an outer struct which is a union of all the possible types. For example, if you have types Foo, Bar, and Baz, define a type like:
struct Outer { union { foo @0 :Foo; bar @1 :Bar; baz @2 :Baz; } }How to access a union depends on the language, but usually there is a which() method that returns an enum value specifying which field is filled in, and then you use the regular getter methods for a nested struct.
Note that both ends have to use this Outer type. You can't serialize a message with a root type of Foo and then parse it as an Outer -- the message has to be created with type Outer. In general there is no way to distinguish different Cap'n Proto types based on the bytes alone.
更多推荐
发布评论