protobuf使用例子

选择你需要的版本丢到你的C:\Program Files\中去,并加好环境变量即可。
加完以后可以在cmd命令行中试试是否有效。

例子使用的版本为:protoc-3.2.0-win32

Microsoft Windows [版本 6.3.9600]
(c) 2013 Microsoft Corporation。保留所有权利。

C:\Users\Ddll>protoc
Missing input file.

C:\Users\Ddll>
  • 定义你的proto文件结构
syntax = "proto3";

option java_package = "类的包名";
option java_outer_classname = "Master2S_ServerListRespProto(类文件名字)";

message Master2S_ServerListResp{
    repeated    ServerList  list = 2;
}

message ServerList{
    int32       sid = 1;
    string      ip  = 2;
}
  • 导出代码
protoc --java_out=需要存放代码的根目录 -I proto搜索目录 proto具体文件路径到文件

执行完以后,会在你指定的位置生成对应名字为Master2S_ServerListRespProto的文件。

  • 使用说明

    1.生成字节数据

        Master2S_ServerListRespProto.Master2S_ServerListResp.Builder builder
                = Master2S_ServerListRespProto.Master2S_ServerListResp.newBuilder();
        for(ServerInfo info : sInfos){
            Master2S_ServerListRespProto.ServerList.Builder list = Master2S_ServerListRespProto.ServerList.newBuilder();
            list.setIp(info.getHost());
            list.setSid(info.getId());
            builder.addList(list);
        }
        Master2S_ServerListRespProto.Master2S_ServerListResp resp = builder.build();
        resp.toByteArray(); //你需要的字节数据

ServerInfo 为一个简单属性类

public class ServerInfo {
    private int sid;
    private String ip;
    ......
}

2.解析字节数据

        try {
            Master2S_ServerListRespProto.Master2S_ServerListResp resp
                    = Master2S_ServerListRespProto.Master2S_ServerListResp.parseFrom(bytes);
            for(Master2S_ServerListRespProto.ServerList list : resp.getListList()){
                list.getSid(); // 你需要的数据
                list.getIp();  // 你需要的数据
            }
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
  • bytes属性使用说明

    除了基本的数据属性外,还可以直接定义bytes类型属性字段。和普通属性使用不同,需要用到protobuf提供的中间类com.google.protobuf.ByteString。ByteString.copyFrom 把bytes转为bytestring,ByteString.toByteArray转为需要的bytes数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值