一、配置protobuf开发环境
二、创建 .proto 文件,定义数据结构
//message.proto
syntax = "proto2";
package Message;
message MessageTest{
required int64 dateTime = 1;
required string hostName = 2;
required string ip = 3;
required string info = 4;
// 字段规则:required -> 字段只能也必须出现 1 次
// 字段规则:optional -> 字段可出现 0 次或1次
// 字段规则:repeated -> 字段可出现任意多次(包括 0)
// 类型:int32、int64、sint32、sint64、string、32-bit ....
// 字段编号:0 ~ 536870911(除去 19000 到 19999 之间的数字)字段规则 类型 名称 = 字段编号;
三、编译.proto文件
protoc --cpp_out=./ message.proto
项目目录下会生成message.pb.h
和message.pb.cc
文件
四、编写writer文件
//writer.cpp
#include "message.pb.h"
#include <fstream>
#include <iostream>
#include <sys/time.h>
using namespace std;
using namespace Message;
int main(void){
MessageTest msg;
struct timeval tv;
struct timezone tz;
gettimeofday(&tv,&tz);
const long dateTime = tv.tv_sec;
msg.set_datetime(dateTime);
msg.set_hostname("dataNode-1000");
msg.set_ip("192.168.0.128");
msg.set_info("Everything is normal, I'm healthy");
fstream output("message.db",ios::out|ios::trunc|ios::binary);
if(!msg.SerializeToOstream(&output)){
cerr << "save data error." << endl;
return -1;
}
return 0;
}
编译
g++ -Wall -o writer writer.cpp message.pb.cc -lprotobuf -std=c++11
./writer
文件下生成:
五、编写reader文件
#include "message.pb.h"
#include <fstream>
#include <iostream>
using namespace std;
using namespace Message;
void traceMsg(const MessageTest &msg){
cout << msg.datetime() << endl;
cout << msg.hostname() << endl;
cout << msg.ip() << endl;
cout << msg.info() << endl;
}
int main(void){
MessageTest msg;
fstream input("message.db",ios::in|ios::binary);
if(!msg.ParseFromIstream(&input)){
cerr << "read data from file error." << endl;
return -1;
}
traceMsg(msg);
return 0;
}
g++ -Wall -o reader read.cpp message.pb.cc -lprotobuf -std=c++11
./reader