# study-protobuf **Repository Path**: zebias/study-protobuf ## Basic Information - **Project Name**: study-protobuf - **Description**: 学习protobuf协议 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-08-18 - **Last Updated**: 2021-09-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 学习ProtoBuf协议 1. 版本需要对应首先需要现在protoc.exe文件,如果你是在windows系统中使用的话 下载地址:https://github.com/protocolbuffers/protobuf/releases/tag/v3.13.0-rc3 找到 protoc-3.13.0-rc-3-win64.zip 下载。 ### Proto使用方法: 1. 创建*.proto文件 - 协议说明: 1. 注释: // 2. 选择哪个版本协议 syntax = "proto2" 或 syntax = "proto3" - 参数说明: 1. 定义一个协议类型 字符规则: |字段规则(required)|字段类型(int32)|字段名称(age)|字段标识号(1)| ----- 字段规则: a. required: 该值必须设置 b. optional: 可以不设置,不设置则不会编码进去;解码后是默认值 c. repeated: 字段可以重复任意多次(包括0次),类似于List,Vector数组 字段类型: double,float,int32,sint32:编码为负数时,比int32高效,int64,sint64,fixed32 fixed64,sfixed32,sfixed64,bool:utf-8 或 7-bit ascii,string,bytes 2. 枚举 示例: enum Direction { START = 0; EAST = 1; SOUTH = 2; WEST = 3; NORTH = 4; }; - 关键字说明: 1. 包:防止不同消息类型,存在命名冲突。 c/c++是命名空间 package test; 2. message的嵌套使用 message address_book { repeated myperson persons = 1; //人物联系表 } - 协议差异 1. proto3和proto2的区别 (1) 移除required (2) optional改为singular(也去掉) (3) 移除了deafault选项,proto3中,字段的默认值只能根据字段类型由系统决定 (4) 枚举类型的第一个字段必须为0 - gRPC远程过程调用 ```protobuf // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } ``` 2. 生成java文件 ```shell script .\protoc.exe --java_out=E:\project\dev\gradle\study\study-protobuf\src\main\java\ -I E:\project\dev\gradle\study\study-protobuf\src\main\java\ E:\project\dev\gradle\study\study-protobuf\src\main\java\org\zebias\study\netty\codec\potobuf\SubscribeReq.proto ``` 参数说明: protoc --java_out 【des-dir】 【source-file】 protoc --java_out 【des-dir】 --proto_path(-I) 【source-file】 -- java_out 3. 引入jar包 ```groovy // https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java compile group: 'com.google.protobuf', name: 'protobuf-java', version: '3.13.0-rc-3' ``` ### 创建项目进行socket通信 1. 服务端 2. 客户端