Protobuf和FlatBuffers以及ByteBuffer的应用

简介:
首先来一发pb3的IDL代码Helloworld.proto
syntax = "proto2";

package proto.helloworld;

message HelloWorld
{
    required int32 id = 1;         //  id
    required  string str = 2;     //  str
    optional int32 opt = 3;         //  optional field
}

使用命令行或者编写一个bat批处理文件
@set path=..\..\..\..\third_party\protobuf\bin\release;%path%
@cls

::  //////////////////////////////////////////////////////////// /
::
:: 编译Protobuf协议
::
::  //////////////////////////////////////////////////////////// /
protoc --version

protoc --cpp_out=../ ./Helloworld.proto

pause
执行以上的批处理文件,将会在其目录的上一层目录下生成两个源码文件:Helloworld.pb.h和Helloworld.pb.cc.
将生成的这俩文件拖进工程里面去,至于vc的StdAfx,预编译头的问题,很好解决.在cc文件上点右键->属性->C/C++->预编译头->预编译头(不使用预编译头),这事儿就妥妥的解决了.

以下列举序列化到三种目标里去的实例
1.std::string
void testString()
{
     //////////////////////////////////////////////////////////////////////// //
     //  编码
     //////////////////////////////////////////////////////////////////////// //
    proto::helloworld::HelloWorld msg_encode;
    msg_encode.set_id(10086);
    msg_encode.set_str("hello world");
    msg_encode.set_opt(10000);

    std:: string str_data;
     bool encode_ok = msg_encode.SerializeToString(&str_data);
    ASSERT(encode_ok);

     //////////////////////////////////////////////////////////////////////// //
     //  解码
     //////////////////////////////////////////////////////////////////////// //
    proto::helloworld::HelloWorld msg_decode;
     bool decode_ok = msg_decode.ParseFromString(str_data);
    ASSERT(decode_ok);
    size_t n = str_data.length();

    ASSERT(msg_decode.id() == 10086);
    ASSERT(msg_decode.str().compare("hello world") == 0);
    ASSERT(msg_decode.opt() ==  10000 );
}

2.ByteArray(char [])
void testByteArray()
{
     //////////////////////////////////////////////////////////////////////// //
     //  编码
     //////////////////////////////////////////////////////////////////////// //
    proto::helloworld::HelloWorld msg_encode;
    msg_encode.set_id(10086);
    msg_encode.set_str("hello world");
    msg_encode.set_opt(10000);

     char msg_buf[1024];
    ZeroMemory(msg_buf,  sizeof(msg_buf));
     bool encode_ok = msg_encode.SerializeToArray(msg_buf,  sizeof(msg_buf));
    ASSERT(encode_ok);
     int encode_size = msg_encode.ByteSize();

     //////////////////////////////////////////////////////////////////////// //
     //  解码
     //////////////////////////////////////////////////////////////////////// //
    proto::helloworld::HelloWorld msg_decode;
     bool decode_ok = msg_decode.ParseFromArray(msg_buf, encode_size);
    ASSERT(decode_ok);

    ASSERT(msg_decode.id() == 10086);
    ASSERT(msg_decode.str().compare("hello world") == 0);
    ASSERT(msg_decode.opt() == 10000);
}

3.std::fstream
void testStream()
{
     //////////////////////////////////////////////////////////////////////// //
     //  编码
     //////////////////////////////////////////////////////////////////////// //
    proto::helloworld::HelloWorld msg_encode;
    msg_encode.set_id(10086);
    msg_encode.set_str("hello world");
    msg_encode.set_opt(10000);

    std::fstream output("./msg_bin", std::ios:: out | std::ios::trunc | std::ios::binary);
     bool encode_ok = msg_encode.SerializeToOstream(&output);
    ASSERT(encode_ok);
    output.close();

     //////////////////////////////////////////////////////////////////////// //
     //  解码
     //////////////////////////////////////////////////////////////////////// //
    std::fstream input("./msg_bin", std::ios:: in | std::ios::binary);
    proto::helloworld::HelloWorld msg_decode;
     bool decode_ok = msg_decode.ParseFromIstream(&input);
    ASSERT(decode_ok);

    ASSERT(msg_decode.id() == 10086);
    ASSERT(msg_decode.str().compare("hello world") == 0);
    ASSERT(msg_decode.opt() == 10000);
}
以上就是ProtoBuf的基本用法了.


FlatBuffers

FlatBuffers支持将ProtoBuf的IDL转换为自己的IDL,只需要简单的一行命令:
flatc.exe --proto Helloworld.proto
该命令将会生成一个FlatBuffers的IDL文件:Helloworld.fbs.

Helloworld.fbs它看起来像是这样的:
//  Generated from Helloworld.proto

namespace fbs.helloworld;

table HelloWorld {
  id: int = 0 (id: 0);
  str: string (required, id: 1);
  opt: int = 0 (id: 2);
}

//  定义之后将会提供GetHelloWorld,VerifyHelloWorldBuffer,FinishHelloWorldBuffer三个方法.
root_type HelloWorld;
这是我基于生成的IDL修改过的.

我们可以用下面这个bat去生成代码:
flatc.exe --cpp -o ../ Helloworld.fbs
pause
执行之后,它将在当前目录的上一层目录下生成一个代码文件:Helloworld_generated.h

使用方法大概是这样的:
void testFlatBuffer()
{
     //////////////////////////////////////////////////////////////////////// //
     //  编码
     //////////////////////////////////////////////////////////////////////// //

    flatbuffers::FlatBufferBuilder builder;

    int32_t id = 10086;
     const  char *str = "hello world";
    int32_t opt = 10000;

#if 0
    auto strName = builder.CreateString(str);
    auto root = fbs::helloworld::CreateHelloWorld(builder, id, strName, opt);
#else
    auto root = fbs::helloworld::CreateHelloWorldDirect(builder, id, str, opt);
#endif

#if 0
    builder.Finish(root);
#else
    FinishHelloWorldBuffer(builder, root);
#endif

    auto p = builder.GetBufferPointer();
    auto sz = builder.GetSize();

    auto bufferpointer =
        reinterpret_cast< const  char *>(builder.GetBufferPointer());
    std:: string buffer;
    buffer.assign(bufferpointer, bufferpointer + builder.GetSize());
    size_t n = buffer.length();

    builder.ReleaseBufferPointer();

     //////////////////////////////////////////////////////////////////////// //
     //  解码
     //////////////////////////////////////////////////////////////////////// //
#if 0
    auto decode = flatbuffers::GetRoot<proto::helloworld::HelloWorld>(buffer.c_str());
#else
    auto decode = fbs::helloworld::GetHelloWorld(buffer.c_str());
#endif
    assert(decode->id() == 10086);
    assert( strcmp(decode->str()->c_str(), "hello world") == 0);
    assert(decode->opt() == 10000);
}



ByteBuffer
关于这个嘛,看以前的文章:http://www.cppblog.com/tx7do/archive/2015/06/12/145865.html
协议定义如下:
#include "ByteBuffer.h"

//  声明序列化
#define NET_APPEND(STRUCT_TYPE)\
     static ByteBuffer&  operator<<(ByteBuffer& lht,  const STRUCT_TYPE& rht)

//  声明解序列化
#define NET_READ(STRUCT_TYPE)\
     static  const ByteBuffer&  operator>>( const ByteBuffer& lht, STRUCT_TYPE& rht)

namespace bb
{
     namespace helloworld
    {

         struct CMD_HelloWorld
        {

            int32            id;         //  id
            std:: string        str;     //  str
            int32            opt;     //  optional field

            CMD_HelloWorld()
            {
                 this->id = 0;
                 this->opt = 0;
                 this->str.clear();
            }
        };
        NET_APPEND(CMD_HelloWorld)
        {
            lht << rht.id
                << rht.str
                << rht.opt;
             return lht;
        };
        NET_READ(CMD_HelloWorld)
        {
            lht >> rht.id
                >> rht.str
                >> rht.opt;
             return lht;
        };


    }
}
使用的代码是这样的:
void testByteBuffer()
{
     //////////////////////////////////////////////////////////////////////// //
     //  编码
     //////////////////////////////////////////////////////////////////////// //
    bb::helloworld::CMD_HelloWorld msg_encode;
    msg_encode.id = 10086;
    msg_encode.str = "hello world";
    msg_encode.opt = 10000;

    ByteBuffer sendBuffer;
    sendBuffer.clear();
    sendBuffer << msg_encode;
    
    auto p = sendBuffer.contents();
    auto sz = sendBuffer.size();
    
     //////////////////////////////////////////////////////////////////////// //
     //  解码
     //////////////////////////////////////////////////////////////////////// //
    ByteBuffer recvBuffer;
    recvBuffer.clear();
    recvBuffer.append((uint8*)p, sz);
        bb::helloworld::CMD_HelloWorld msg_decode;
    recvBuffer >> msg_decode;

    assert(msg_decode.id == 10086);
    assert(strcmp(msg_decode.str.c_str(), "hello world") == 0);
    assert(msg_decode.opt == 10000);
}


总结
相比PB来说,FBS不需要额外的指定一个外部的缓存,它内置了一个缓存,大概这就是它快的缘故吧.
序列化之后的空间占用结果是: protobuf: 19  flatbuffers: 48  bytebuffer: 20.
从空间上看,FBS是并不占优啊.
以前,一直使用的是ByteBuffer,因为简单,而且无论是从空间上还是时间上都还算划算.但是要手写序列化的代码,相对来说,比较烦人.所以还是PB,FBS这样的利用IDL自动生成代码的方式方便.
PB现在支持几乎所有语言,是一个相当成熟的解决方案了.
FBS就目前来说,支持的语言并不多,官方只支持:C++ ,Java ,C# ,Go ,Python ,JS ,C ,PHP ,Ruby.
PB的IDL各大编辑器几乎都支持它的语法染色,然而FBS却并没有,这个看起来也很让人蛋疼.
PB相对慢,但是空间占用小,它更适合外网传输,并且对时间并不是那么要求高的应用;
FBS相对快,但是空间占用较大,它在RPC,内网传输,以及对时间要求很高的场景上会很适合,在手机登移动平台下,计算性能不高的场景下也是适合的.
总的来说,我要做网游的通讯协议,还是PB更加的适合.
FBS更适合的是Android,iOS这样的移动平台,因为它们对性能要求比较高,使用FBS能够有效的提高性能.
目录
相关文章
|
9天前
|
人工智能 JSON 安全
Fastjson远程代码执行漏洞,阿里云AI安全为您保驾护航
阿里云AI安全产品联动防御Fastjson攻击
2334 12
Fastjson远程代码执行漏洞,阿里云AI安全为您保驾护航
|
9天前
|
云安全 人工智能 安全
|
9天前
|
人工智能 自然语言处理 数据挖掘
Qwen3.8-Max-Preview深度全解析:2.4万亿参数旗舰MoE模型+Token Plan限时优惠完整落地指南
2026年7月,全新旗舰级混合专家大模型Qwen3.8-Max-Preview正式开放抢先体验,作为通义千问Qwen3系列规格最高、综合推理能力顶尖的新一代模型,该模型总参数量达到2.4万亿(2.4T),是当前线上可调用的原生多模态旗舰模型,综合推理水准对标海外顶级Fable 5模型,在复杂工程开发、长文档深度分析、多步骤智能体自治、跨境多语言创作、海量数据挖掘五大高难度业务场景实现跨越式性能提升。
1053 2
|
9天前
|
人工智能 自然语言处理 数据挖掘
最新版通义千问(Qwen3.8-Max-Preview)功能介绍
2026年,通义千问正式推出全新旗舰级大模型 **Qwen3.8-Max-Preview 预览版**,作为首款突破万亿参数规格的新一代基座模型,该模型总参数量达到**2.4万亿**,采用全新迭代的MoE混合专家架构,综合推理性能、长文本处理、多模态理解、复杂任务规划能力全面超越前代Qwen3.7-Max版本,整体实力跻身全球第一梯队,可对标海外顶级旗舰模型,是当前面向复杂工程开发、多智能体协同、超长文档解析、专业办公自动化场景的最优国产基座模型。
1093 0
|
11天前
|
人工智能
Qwen3.8抢先体验!正式版即将发布并开源!
千问Qwen3.8即将开源,参数达2.4T,进化速度以“天”计,实力媲美Fable 5。预览版Qwen3.8-Max已上线阿里Token Plan等平台,限时优惠:日间Credits低至1折,夜间更优,个人/团队版月付仅35元起!
1053 44
|
7天前
|
自然语言处理 测试技术 API
通义千问Qwen3.8-Max-Preview全功能解析:2.4万亿参数旗舰模型深度使用指南
在大模型技术持续迭代的当下,通义千问推出的Qwen3.8-Max-Preview作为新一代旗舰预览版模型,凭借2.4万亿参数的超大规模、多模态融合能力与全场景适配特性,成为开发者与企业用户探索AI应用的核心工具。该模型采用稀疏混合专家(MoE)架构,是通义千问首个突破万亿参数的多模态模型,可同时处理文本、图像、视频与文档等多种数据形态,在全栈代码开发、复杂逻辑推理、长文档分析与多智能体协作等场景实现跨越式升级。本文将全面拆解Qwen3.8-Max-Preview的核心功能,详解API调用流程与配置方法,覆盖多场景实战技巧,帮助用户快速掌握这款旗舰模型的使用方法,充分释放其性能潜力。
528 1
|
7天前
|
人工智能 前端开发 Linux
Codex 桌面版安装 + CC Switch 接入第三方 API 完整教程(2026 最新)
2026最新教程:手把手教你安装Codex桌面版,通过CC Switch v3.17.0一键接入Fenno等国产API(兼容OpenAI Responses格式),跳过账号登录,完整启用代码审查、多步任务与上下文感知功能。零基础友好,全程图文实操。(239字)
633 0
|
10天前
|
人工智能 自然语言处理 数据挖掘
Qwen3.8-Max 预览版全解析:2.4 万亿参数旗舰模型,Token Plan 限时优惠指南
Qwen3.8-Max-Preview是通义千问Qwen3系列旗舰MoE大模型,参数达2.4万亿,综合推理能力居行业第一梯队。支持思考/快速双模式,擅长大模型五大高难场景。现于阿里云百炼Token Plan、Qoder及QoderWork上线体验,个人版低至39元/月。在阿里云百炼官网:https://t.aliyun.com/U/fPVHqY 免费领取千万Tokens
716 1
Qwen3.8-Max 预览版全解析:2.4 万亿参数旗舰模型,Token Plan 限时优惠指南