Google Protocol Buffers,如何处理多种消息类型? [英] Google Protocol Buffers, how to handle multiple message-Types?

查看:191
本文介绍了Google Protocol Buffers,如何处理多种消息类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获取序列化协议缓冲区消息的类型?

Is it possible to get the Type of the serialized Protocol Buffer message?

我有这个例子

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;
}

在Java中我有这段代码

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 determine if the file contains a Address or a User? What is the common way to handle multiple Message-Types? How can I determine which Message-Type I have received?

推荐答案

我们无法确定该文件是包含地址还是用户。因为数据中没有编码类型信息。

We cannot determine if the file contains a Address or a User. Because there is not type information encoded in the data.

要处理多个消息类型,您可以使用以下元数据:

To handle multiple Message-Types, you can use meta data like:


  • 文件名扩展名

  • HTTP中的标题

  • 帧基流协议中的特定帧头

  • ...

  • Extension of the filename
  • Headers in HTTP
  • Specific frame header in frame base stream protocol
  • ...

这篇关于Google Protocol Buffers,如何处理多种消息类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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