ProtoBuf例程(Java & C)

说明:该示例使用Java与C进行Socket通信(该部分代码省略),数据通过ProtoBuf压缩传输。

ProtoBuf安装:https://blog.csdn.net/jl_gao/article/details/81114800

proto文件:

syntax = "proto2";
option java_package = "com.xxx.protobuf.sample";
option java_outer_classname = "Sample_Amessage";
option java_multiple_files = true;
message AMessage
{
  required int32 a=1;
  optional int32 b=2;
}

将proto文件批量生成java & C文件的脚本:(该脚本与proto文件在同一级目录下)

@echo off
::检查protobuf安装
protoc --version >nul
if ERRORLEVEL 1 (echo "check protoc cmd failed") else (echo "check protoc cmd success")
protoc-c --version >nul
if ERRORLEVEL 1 (echo "check protoc-c cmd failed") else (echo "check protoc-c cmd success")

::遍历proto文件,生成java
for /f "delims=" %%i in ('dir /b /a-d /s "*.proto"') do (
    echo "converting %%~nxi"
    protoc --proto_path=. --java_out=../java %%~nxi
    protoc --proto_path=. --c_out=../C  %%~nxi
)

pause

Java端:

(生成三个文件:AMessage.java,AmessageOrBuilder.java,Sample_Amessage.java)

public void testLocal_AMessage(byte[] data){
    // ProtoBuf数据转Java对象
    // data 是byte[]类型的数据
    AMessage decodeMsg = AMessage.parseFrom(data);

    // Java对象转ProtoBuf数据
    AMessage.Builder builder = AMessage.newBuilder();
    builder.setA(100);
    builder.setB(200);
    AMessage sendMsgObj = builder.build();

    byte[] encodeMsg = sendMsgObj.toByteArray();
}

C端:

(生成两个文件:amessage.pb-c.h,amessage.pb-c.c)

// 测试本地protobuf
void testLocal_Amessage(){
    AMessage msg = AMESSAGE__INIT;
    msg.a = 10;
    msg.has_b = 1;
    msg.b = 20;
    printf("testLocal_Amessage:pack:a=%d,b=%d\n", msg.a, msg.b);

    size_t packSize = amessage__get_packed_size(&msg);
    uint8_t* buf = (uint8_t*)malloc(packSize);
    amessage__pack(&msg, buf);

    // 本地decode
    AMessage* decodeMsg = amessage__unpack(NULL, packSize, buf);
    printf("testLocal_Amessage:unpack:a=%d, b=%d\n", decodeMsg->a, decodeMsg->b);
    amessage__free_unpacked(decodeMsg, NULL);

    free((void*)buf);
}

 

你可能感兴趣的:(protobuf)