1. Introduction to ProtoBuf
Protocol Buffers (aka protobuf) is Google's language-independent, platform-independent, and extensible structured data serialization mechanism. He is Google's data interchange format, which can be used for network communication and data storage.
Protobuf facilitates the reading of data streams in various languages by defining the structure of the data and then using the source code generated by the protoc tool (including C#, java, C++, Python, etc.).
Official tutorials for developers on how to use protobuf:
https://developers.google.com/protocol-buffers/docs/tutorials
Examples: https://github.com/protocolbuffers/protobuf/blob/master/examples
Full documentation for Protocol Buffers is available at:
https://developers.google.com/protocol-buffers/
Two, protoc compiler
The protocol compiler is written in C++, we can directly download the compiled exe.
URL on github: https://github.com/protocolbuffers/protobuf
Compiled version: https://github.com/protocolbuffers/protobuf/releases
Protoc 64 is the download address: protoc-3.18.1-win64.zip
Full version download address: protobuf-all-3.18.1.zip
Under the bin directory after decompression: protoc.exe can directly generate codes in various languages according to the defined structure.
// 输出c#代码
protoc --csharp_out=./ telegram.proto
// 输出java代码
protoc --java_out=./ telegram.proto
3. The .proto file
protobuf needs to define a data structure description file to describe the content of the data.
The following is an example of the official website:
syntax = "proto3"; // proto3 必须加此注解
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
enum Corpus {
UNIVERSAL = 0;
WEB = 1;
IMAGES = 2;
LOCAL = 3;
NEWS = 4;
PRODUCTS = 5;
VIDEO = 6;
}
Corpus corpus = 4;
}
The above is a message defined. Contains:
query of String type, number 1
page_number of int type, number 2
corpus of enumeration type
Four, C #, java use
Simple use is as follows:
C# example
// 定义对象,复制
Telegram data = new Telegram ();
data.UserCode = 76157;
data.Status = RunStaus.Loaded;
// 计算大小
int size = data.CalculateSize();
Console.WriteLine(size);
// 输出对象到文件
FileStream fso = new FileStream("test.data", FileMode.Create);
data.WriteTo(fso );
fsfso Close();
// 读取文件生成对象
FileStream fsi = new FileStream("test.data", FileMode.Open);
Telegram data2 = new Telegram ();
data2.MergeFrom(fsi );
fsi .Close();
Java example
Telegram data= Telegram.newBuilder().setUserCode(1).setStatus(RunStaus.Loaded);
// 输出对象到为Byte数组
for(byte byte : data.toByteArray()){
System.out.println(byte);
}
// 转化Byte数组为对象
Telegram data2= null;
try {
data2= Telegram.parseFrom(data.toByteArray());
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
System.out.println(data2.toString());