java中使用protobuf

有事找周文發表於2018-08-17

專案中用到protobuf與服務端進行通訊,主要就是一個資料傳輸的作用,用protobuf組織引數相對來說小一點,簡潔些。其實protobuf的作用和json一個性質。

專案主要是通過protobuf和服務端進行通訊完成業務功能。

用到了protobuf+zmq

步驟:

1.編譯protobuf的.proto檔案獲取java類檔案。

編譯--------

生成--------

2.根據與服務端敲定的協議組織引數

 

3.ZMQ傳送訊息

完成:

------------------------------------------------------------------------程式碼------------------------------------------------------------------------------------------

package com.czht.wdp.auto;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.stream.FileImageInputStream;

import org.zeromq.ZMQ;
import org.zeromq.ZMQException;

import com.czht.wdp.protobuf.FacedataProcess;
import com.czht.wdp.protobuf.FacedataProcess.Message;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

/**
* 描述:自動化模擬通行閘機
* @author create or edit by zhouwen
* @date 2018年8月17日--上午9:56:04
*/
public class StartTestting01 {

	public static void main(String[] args){
		byte[] reply = null;
		ZMQ.Socket socket = null;
		try {
			ZMQ.Context context = ZMQ.context(1);
			socket = context.socket(ZMQ.REQ);
			String url = "tcp://192.168.10.29:6610";
			socket.connect(url);//繫結地址
		} catch (ZMQException e) {
			throw e;
		}
		byte[] bytes = new byte[1024];
		while (true) {//伺服器一直迴圈
			
			FacedataProcess.Device_Capture.Builder  dc=  FacedataProcess.Device_Capture.newBuilder();
			FacedataProcess.Face_Param.Builder  fp=  FacedataProcess.Face_Param.newBuilder();
			fp.setFaceHeight(100);
			fp.setFaceWidth(100);
			fp.setFaceLeftTopY(100);
			fp.setFaceLeftTopX(100);
			
			dc.setDeviceIp("192.168.17.153");
			dc.setPassDatetime(20180817140000L);
		    dc.setFaceparam(fp);
			//byte[] image2byte = image2byte("D:\\pic\\1.jpg");
		    for (int i = 1; i < 10; i++) {
		    	String path = "D:\\pic\\zhouwen-0"+i+".jpg";
		    	System.err.println(path);
			    byte[] image2byte = imageToByteArray(path);
			    System.err.println("圖片檔案陣列長度:"+image2byte.length);
				dc.setScenegraphData(ByteString.copyFrom(image2byte));
		        //
				FacedataProcess.Request request = FacedataProcess.Request.newBuilder().setDeviceCapture(dc.build()).build();
				//構造訊息
				FacedataProcess.Message message = FacedataProcess.Message.newBuilder().setType(FacedataProcess.MessageType.MsgGateCapture).setRequest(request).build();
				byte[] byteArray = message.toByteArray();
				socket.send(byteArray);
				reply = socket.recv();
				FacedataProcess.Message messages = null;
				Message parseFrom;
				try {
					parseFrom = messages.parseFrom(reply);
					System.err.println(parseFrom.getType());
					System.err.println(parseFrom.getResponse().getResult());
					System.err.println(parseFrom.getResponse().getErrCode());
					System.err.println("==================================================================");
					System.err.println("******************************************************************");
					System.err.println("==================================================================");
				} catch (InvalidProtocolBufferException e1) {
					e1.printStackTrace();
				}
		        try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} 
	}

	public static byte[] image2byte(String path){
	    byte[] data = null;
	    FileImageInputStream input = null;
	    try {
	      input = new FileImageInputStream(new File(path));
	      ByteArrayOutputStream output = new ByteArrayOutputStream();
	      byte[] buf = new byte[1024];
	      int numBytesRead = 0;
	      while ((numBytesRead = input.read(buf)) != -1) {
	      output.write(buf, 0, numBytesRead);
	      }
	      data = output.toByteArray();
	      output.close();
	      input.close();
	    }
	    catch (FileNotFoundException ex1) {
	      ex1.printStackTrace();
	    }
	    catch (IOException ex1) {
	      ex1.printStackTrace();
	    }
	    return data;
	  }
	
	public static byte[] imageToByteArray(String imgPath) {
		BufferedInputStream in;
		try {
		in = new BufferedInputStream(new FileInputStream(imgPath));
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int size = 0;
		byte[] temp = new byte[1024];
		while((size = in.read(temp))!=-1) {
			out.write(temp, 0, size);
		}
		in.close();
		return out.toByteArray();
		} catch (IOException e) {
		e.printStackTrace();
		return null;
		}
		} 
}

=============================================================================================

在 Java 中使用 protobuf

https://github.com/google/protobuf/releases 下載編譯器,並設定環境變數。

建立java專案新增protobuf-java引用

compile group: 'com.google.protobuf', name: 'protobuf-java', version: '3.2.0'

編寫.proto檔案

syntax = "proto3";

message Person {
    int32 id = 1;
    string name = 2;

    repeated Phone phone = 4;

    enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
    }

    message Phone {
        string number = 1;
        PhoneType type = 2;
    }
}

使用下面命令編譯出.java檔案

protoc --java_out=./java ./proto/message.proto 

編寫java檔案測試

public class Main {
    public static void main(String[] args) {
        Message.Person.Builder personBuilder = Message.Person.newBuilder();
        personBuilder.setId(12345678);
        personBuilder.setName("Admin");
        personBuilder.addPhone(Message.Person.Phone.newBuilder().setNumber("10010").setType(Message.Person.PhoneType.MOBILE));
        personBuilder.addPhone(Message.Person.Phone.newBuilder().setNumber("10086").setType(Message.Person.PhoneType.HOME));
        personBuilder.addPhone(Message.Person.Phone.newBuilder().setNumber("10000").setType(Message.Person.PhoneType.WORK));

        Message.Person person = personBuilder.build();
        byte[] buff = person.toByteArray();

        try {
            Message.Person personOut = Message.Person.parseFrom(buff);
            System.out.printf("Id:%d, Name:%s\n", personOut.getId(), personOut.getName());

            List<Message.Person.Phone> phoneList = personOut.getPhoneList();

            for (Message.Person.Phone phone : phoneList) {
                System.out.printf("PhoneNumber:%s (%s)\n", phone.getNumber(), phone.getType());
            }

        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

        System.out.println(Arrays.toString(buff));

    }
}

執行結果

Id:12345678, Name:Admin
PhoneNumber:10010 (MOBILE)
PhoneNumber:10086 (HOME)
PhoneNumber:10000 (WORK)
[8, -50, -62, -15, 5, 18, 5, 65, 100, 109, 105, 110, 34, 7, 10, 5, 49, 48, 48, 49, 48, 34, 9, 10, 5, 49, 48, 48, 56, 54, 16, 1, 34, 9, 10, 5, 49, 48, 48, 48, 48, 16, 2]

Process finished with exit code 0

 

相關文章