本文主要是介绍Google Protocol Buffer(GPB)使用之完全解析二:有了GPB的日子怎么过?什么是GPB?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
通过前面博文的学习,我们知道:没有GPB,客户端的日子很难过,现在略作回顾,没有GPB的日子是这样的:
#include <iostream>
#include <fstream>
using namespace std;int main()
{ int id = 123456; // 字段idchar 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
这篇关于Google Protocol Buffer(GPB)使用之完全解析二:有了GPB的日子怎么过?什么是GPB?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!