項目中有用到 protobuf 做跨平臺的通訊 , 本身也想寫個demo學習實踐一下, 因而有了本文。java
*這個demo是基於java開發的
dom
1.系統環境socket
Windows學習
2.所需軟件和libui
1). protoc.exe
編碼
2). protobuf-java-2.4.1.jarspa
3.demo簡介.net
很簡單的程序,基於java開發。功能是客戶端把 "消息"(手機信息) 發送給 服務端。服務端收到消息後打印。code
4.開發流程server
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"
至此完成,僅做筆記。