Protobuf使用例子.docVIP

  • 11
  • 0
  • 约5.24千字
  • 约 14页
  • 2016-09-20 发布于重庆
  • 举报
Protobuf使用例子

Protobuf使用例子 rotobuf使用整理 rotobuf序列化反序列化的一种解决方案roto文件编写 执行生成java文件 通过socket进行通信 下载官方提供的protobuf-java.xx.jar包,然后就可以进行开发工作了Jprotobuf使用整理 jprotobuf操作 将工程从github拉到本地eclipse中,增加一个打包bat脚本,将工程打成jar包客户端用proto文件生成的字节码发送请求数据,服务端用注解方式接收数据然后发送数据客户端代码为: 通过socket方式处理 // JPClient.java文件为: public class JPClient { private final static String HOST_NAME = localhost; private final static int PORT = 8080; public static void main(String[] args) { Socket socket = null; InputStream ins = null; OutputStream ous = null; try { socket = new Socket(HOST_NAME, PORT); socket.setKeepAlive(true); socket.setSoTimeout(10000); ous = socket.getOutputStream(); ins = socket.getInputStream(); UserInfo.Builder builder = UserInfo.newBuilder(); builder.setUserId(10501L); builder.setUserName(jprotobuf); ListString mobileList = new ArrayListString(); mobileList.add; mobileList.add; builder.addAllMobileList(mobileList); builder.setFlag(1); builder.setVipStatus(true); // protobuf提供的toByteArray方法实现序列化处理 byte[] bytes = builder.build().toByteArray(); int length = bytes.length; ous.write(length); ous.write(bytes); ous.flush(); System.out.println(length= + length); System.out.println(builder= + builder.build().toString()); int readLength = ins.read(); byte[] readBytes = new byte[readLength]; ins.read(readBytes, 0, readLength); System.out.println(readLength= + readLength); // protobuf提供的parseFrom实现反序列化处理 UserInfo userInfo = UserInfo.parseFrom(readBytes); System.out.println(userInfo= + userInfo.toString()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) {

文档评论(0)

1亿VIP精品文档

相关文档