Protocol Buffers (ProtocolBuffer/ protobuf )是Google公司开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。现阶段支持C++、JAVA、Python等三种编程语言。
2.protobuf相比Xml的优点
•更简单
•数据描述文件只需原来的1/10至1/3
•解析速度是原来的20倍至100倍
•减少了二义性
•生成了更容易在编程中使用的数据访问
因为protobuf是采用二进制的序列化方式,因此非常适合网络传输
google protobuf序列化可以不需要包含消息长度或者类型
google::protobuf::Message* ProtobufCodec::createMessage(const std::string& typeName)
{
google::protobuf::Message* message = NULL;
const google::protobuf::Descriptor* descriptor =
google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(typeName);
if (descriptor)
{
const google::protobuf::Message* prototype =
google::protobuf::MessageFactory::generated_factory()->GetPrototype(descriptor);
if (prototype)
{
message = prototype->New();
}
}
return message;
}
通过文件名然后可以得到Descriptor*然后再得到消息类型
muduo protobuf传输格式
struct ProtobufTransportFormat __attribute__ ((__packed__))
{
int32_t len;
int32_t nameLen;
char typeName[nameLen];
char protobufData[len-nameLen-8];
int32_t checkSum; // adler32 of nameLen, typeName and protobufData
};