博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用protobuf定义消息
阅读量:2229 次
发布时间:2019-05-09

本文共 1840 字,大约阅读时间需要 6 分钟。

下载protobuf-2.3.0:
    
安装: 
unzip protobuf-2.3.0.zip
cd protobuf-2.3.0
./configure
make 
make check 
make install

结果:
Libraries have been installed in:
   /usr/local/lib
Head files hava been installed in:
/usr/local/include/google/
protobuf/
开始写.proto文件:
BaseMessage.proto:
message MessageBase
{

    required int32 opcode = 1;
    // other: sendMgrId, sendId, recvMgrId, recvId, ...
}

message BaseMessage
{

    required MessageBase msgbase = 1;
}
BaseMessage.proto是其它消息proto文件的基础,以容器模块的C2S_GetContainerInfo为例:
ContainerMessage.proto:
import "BaseMessage.proto";

message C2SGetContainerInfoMsg
{

    required MessageBase msgbase = 1;
    optional int32 containerType = 2;
}
.proto文件编写规则
1)所有消息都需要包含msgbase这项,并编号都为1,即:
  required MessageBase msgbase = 1;
2)除了msgbase这项写成required外,其它所有项都写成optional。
编译 .proto 文件
protoc -I=. --cpp_out=. BaseMessage.proto
protoc -I=. --cpp_out=. ContainerMessage.proto
生成BaseMessage.pb.h、
    ContainerMessage.pb.h、
将它们添加到工程文件中。
编写C++代码:
1)发送消息:
C2SGetContainerInfoMsg msg;
msg.mutable_msgbase()->set_opcode(C2S_GetContainerInfo);
msg.set_containertype(1);
std::string out = msg.SerializeAsString();
send(sockfd, out.c_str(), out.size(), 0);
2)接收消息
char buf[MAXBUF + 1];
int len;
bzero(buf, MAXBUF + 1);
len = recv(new_fd, buf, MAXBUF, 0);
if (len > 0)
{

    printf("%d接收消息成功:'%s',共%d个字节的数据\n",
            new_fd, buf, len);

    BaseMessage baseMsg;
    std::string data = buf;
    baseMsg.ParseFromString(data);

    int opcode = baseMsg.mutable_msgbase()->opcode();

    printf("opcode=%d\n", opcode);

    switch (opcode)
    {

    case C2S_GetContainerInfo:
    {

        C2SGetContainerInfoMsg msg;
        msg.ParseFromString(data);

        printf("containerType=%d\n", msg.containertype());

        break;
    }
    default:
    {

        break;
    }
    }
}
else
{

    if (len < 0)
        printf("消息接收失败!错误代码是%d,错误信息是'%s'\n",
             errno, strerror(errno));
    close(new_fd);
    return -1;
}
编译C++代码:
Need to link lib:
protobuf
pthread
参考: 
1, Google Protocol Buffer 的使用和原理: 
2,

转载地址:http://dszbb.baihongyu.com/

你可能感兴趣的文章
【Linux】进程的理解(一)
查看>>
【Linux】进程的理解(二)
查看>>
【C语言】深度理解函数的调用(栈帧)
查看>>
【Linux】进程的理解(三)
查看>>
【C++】带头节点的双向线链表的实现
查看>>
【C++】STL -- Vector容器的用法
查看>>
【Linux】Linux中的0644 和 0755的权限
查看>>
【数据结构】有关二叉树的面试题
查看>>
【Linux】内核态和用户态
查看>>
【Linux】HTTP的理解
查看>>
【Linux】HTTPS的理解
查看>>
【操作系统】大小端问题
查看>>
Git上传代码时碰到的问题及解决方法
查看>>
【Linux】vim的简单配置
查看>>
【C++】智能指针
查看>>
【C++】const修饰的成员函数
查看>>
【C++】面向对象的三大特性
查看>>
【C++】智能指针(后续)
查看>>
【C】堆区和栈区的区别
查看>>
【linux】send和recv函数解析
查看>>