Java中的Protobuf使用例子(转)

protobuf接口文件的生成这里就不举例子,只举一下在Java中怎么使用。

1). 定义"消息"的结构,即书写接口定义文件(.proto文件)。本例中,消息包含了"手机信息"。

文件名 mobile.proto

文件内容如下:

message MobilePhone{    
            
    required string               brand = 1 ;    
    required Hardware          hardware = 2;
    repeated string              software = 3;                    

}

message Hardware {

    required int32                    rom = 1; 
    required int32                    ram = 2;      
    required int32                    size = 3 ;    
    
}


2).通过定义的接口文件,生成Mobile.java

执行命令: protoc  --java_out=outputFile sourceFile

上述命令中outputFile 和 sourceFile 指 输出文件和源文件,需替换成实际文件(路径)名,如:

protoc  --java_out=./src   ./proto/mobile.proto


3).创建工程,编码

引入protobuf-java-2.4.1.jar

拷贝Mobile.java至工程

书写客户端,服务端代码。

具体代码如下:

客户端

package com.nevermore.client;

import java.net.Socket;

import com.nevermore.domain.Mobile;

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        Socket socket = new Socket("127.0.0.1",3030);
        Mobile.MobilePhone.Builder builder = Mobile.MobilePhone.newBuilder();
        Mobile.Hardware.Builder hardware = Mobile.Hardware.newBuilder();
        hardware.setRam(2).setRom(16).setSize(5);
        builder.setHardware(hardware)
               .setBrand("Apple")
               .addSoftware("camera")
               .addSoftware("tecent")
               .addSoftware("browser")
               .addSoftware("player");
        byte[] messageBody = builder.build().toByteArray();
    
        int headerLen = 1;
        byte[] message = new byte[headerLen+messageBody.length];
        message[0] = (byte)messageBody.length;
        System.arraycopy(messageBody, 0,  message, 1, messageBody.length);
        System.out.println("msg len:"+message.length);
        socket.getOutputStream().write(message);
    }

}

服务端:

import java.net.ServerSocket;
import java.net.Socket;

import com.nevermore.domain.Mobile;
import com.nevermore.domain.Mobile.MobilePhone;

public class Server {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        ServerSocket serverSock = new ServerSocket(3030);
        Socket sock = serverSock.accept();
        byte[] msg = new byte[256];
        sock.getInputStream().read(msg);
        int msgBodyLen = msg[0];
        System.out.println("msg body len:"+msgBodyLen);
        byte[] msgbody = new byte[msgBodyLen];
        System.arraycopy(msg, 1, msgbody, 0, msgBodyLen);
        MobilePhone phone = Mobile.MobilePhone.parseFrom(msgbody);
        System.out.println("Receive:");
        System.out.println(phone.toString());
    }

}


运行后服务端打印:

Receive:
brand: "Apple"
hardware {
  rom: 16
  ram: 2
  size: 5
}
software: "camera"
software: "tecent"
software: "browser"
software: "player"

转自:http://my.oschina.net/u/1162561/blog/364772

外加一个字符串转整数和整数转字符串的工具:
/**
     * int到byte[]
     * @param i
     * @return
     */
    public static byte[] intToByteArray(int i) {   
          byte[] result = new byte[4];   
          //由高位到低位
          result[0] = (byte)((i >> 24) & 0xFF);
          result[1] = (byte)((i >> 16) & 0xFF);
          result[2] = (byte)((i >> 8) & 0xFF); 
          result[3] = (byte)(i & 0xFF);
          return result;
        }

        /**
         * byte[]转int
         * @param bytes
         * @return
         */
        public static int byteArrayToInt(byte[] bytes) {
               int value= 0;
               //由高位到低位
               for (int i = 0; i < 4; i++) {
                   int shift= (4 - 1 - i) * 8;
                   value +=(bytes[i] & 0x000000FF) << shift;//往高位游
               }
               return value;
         }
上边的方法适合从socket字节流中提取一部分字节来转为整数,但常用的String与int互转还有常用方法:
//字符串转整数
String str = "12345";

int num = Integer.valueOf(str).intValue();

//整数转字符串
int num = 12345;
String str = String.valueOf( num );
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值