protobuf3.1.0的安装见:https://blog.csdn.net/mircosheng/article/details/70141704
安装完protobuf后,新建.proto文件,本文命名为lm.helloworld. proto
在网络通讯系统中,protobuf能够提升通讯效率。消息嵌套可以实现传输较为复杂的消息。
内容如下:
syntax = "proto2";//这里改成proto3编译不通过,原因不明。有知道的麻烦告知一下。
package lm;
message helloworld {
required string name = 1;
required int32 id = 2; // Unique ID number for this person.
optional string email = 3;
//枚举
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
//个人电话信息
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phones = 4;//个人可拥有多个电话
}
//电话本
message AddressBook{
repeated helloworld people=1;//电话本包含多个人的电话信息
}
~
~
执行命令:protoc -I=./ --cpp_out=./ lm.helloworld.proto
生成两个文件:lm.helloworld.pb.h lm.helloworld.pb.cc
写端writer:
#include "lm.helloworld.pb.h"
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <pthread.h>
#include <fstream>
using namespace std;
void add_message(lm::helloworld *person )
{
person->set_name("bruvin");
person->set_id(123);
person->set_email("[email protected]");
char phone_number[6][12]={"13209812233","17832923210","90323221098",\
"13432820164","90887321234","0976321233"};
for(int i=0;i<6;i++){
lm::helloworld::PhoneNumber *msg2=person->add_phones();
msg2->set_number(phone_number[i]);
msg2->set_type(lm::helloworld::MOBILE);
}
}
int main(void)
{
lm::AddressBook addressbook;
// Write the new address book back to disk.
add_message(addressbook.add_people());
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!addressbook.SerializeToOstream(&output)) {
cerr << "Failed to write msg." << endl;
return -1;
}
return 0;
}
读端reader:
#include "lm.helloworld.pb.h"
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <pthread.h>
#include <fstream>
using namespace std;
void ListMsg(const lm::AddressBook &address_book) {
for(int i=0;i<address_book.people_size();i++){//电话本有几个人的的信息
const lm::helloworld& person = address_book.people(i);
cout << person.name() << endl;
cout << person.id() << endl;
if(person.email()!=""){
cout<<"E-mail address: "<<person.email()<<endl;
}
for(int j=0;j<person.phones_size();j++){//该人有几个电话号码
const lm::helloworld::PhoneNumber& phone_number = person.phones(j);
switch(phone_number.type()){
case lm::helloworld::MOBILE:
cout<<"Mobile phone#:";
break;
case lm::helloworld::HOME:
cout<<"Home phone#:";
break;
case lm::helloworld::WORK:
cout<<"Work phone#:";
break;
}
cout<<phone_number.number()<<endl;
}
}
}
int main(int argc, char* argv[]) {
lm::AddressBook address_book;
fstream input("./log", ios::in | ios::binary);
if (!address_book.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
ListMsg(address_book);
}