- protobuf下载地址:gitHub连接
选择你需要的版本丢到你的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数据。