通过前面博文的学习,我们知道:没有GPB,客户端的日子很难过,现在略作回顾,没有GPB的日子是这样的:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int id = 123456; // 字段id
char str[] = "hello world"; // 字段str
// 服务端:把数据写到"log服务器"中
fstream output("log", ios::out | ios::trunc);
output << id << endl;
output << str;
output.close();
int _id;
char line[100];
memset(line, sizeof(line), 0);
// 客户端:从"log服务器"中读取数据
fstream input("log", ios::in);
input.getline(line, sizeof(line));
_id = atoi(line); // (转换要求:客户端必须详尽了解服务端数据格式)
cout << _id << endl;
memset(line, sizeof(line), 0);
input.getline(line, sizeof(line));
cout << line << endl;
input.close();
return 0;
}
在本文中,我们来看看有了GPB后,日子是怎样的?程序如下:
/*
说明:1:
如果你直接将下面程序拷贝过去,那么一定会出现编译错误,因为
还需要其它文件的配合。在本文中,我暂时仅给出这个简单的程序,
目的是为了说明Google Protocol Buffer的方便之处。
2:
在后续的介绍中,我会把相关方法和文件给大家,到时候,大家就
可以正确地运行该程序了,真正体会到Google Protocol Buffer的
方便之处,敬请期待。
*/
#include <iostream>
#include <fstream>
#include "test.pb.h"
#pragma comment(lib, "libprotobuf.lib")
using namespace std;
int main()
{
int stuID = 123456;
char stuName[] = "hello world";
// 服务端:把数据序列化到"log服务器"中
lm::student stu1;
stu1.set_id(stuID);
stu1.set_str(stuName);
fstream output("./log", ios::out | ios::trunc);
stu1.SerializeToOstream(&output); // 序列化
output.close();
// 客户端:将"log服务器"中的数据反序列化
lm::student stu2;
fstream input("./log", ios::in);
stu2.ParseFromIstream(&input); // 反序列化
int theID = stu2.id(); // 读取数据就是这么简单,爽歪歪
string theName = stu2.str(); // 读取数据就是这么简单,爽歪歪
input.close();
cout << theID << endl;
cout << theName << endl;
return 0;
}
log文件的内容如下(用文本文件方式打开):
控制台上的结果为:
我们可以看到,运用GPB机制后,客户端取数据非常简单,不用关心待解析的数据的具体格式,只需傻瓜式地取数据即可,这就是运用GPB后的效果。那么,什么是GPB呢?
千言万语抽象成一句话:GPB就是一种编解码机制(序列化反序列化机制),可以方便你我。
通过上面的介绍,我们终于懂了GPB是什么了,如果你还需要更全面地了解GPB,请参阅:
wikipedia的相关介绍:http://en.wikipedia.org/wiki/Protocol_Buffers
google的相关介绍 :https://developers.google.com/protocol-buffers/docs/overview
在随后的博文中,我们将详尽地介绍如何使用GPB, 敬请期待。