C++ 使用ProtoBuffer 心得

最近要求使用ProtoBuffer来做作为服务器跟客户端传输数据的桥梁。

protobuffer比XML,JSON 好就不说了。
关键就说两个地方
为啥需要说着两个呢,因为他的序列化后在 最前面需要加上长度,而这个并不是真正的长度,是经过一个算法生成的长度。

1. 把本地的字符串转换成  protoBuffer


oCommonMsg.set_type(duolabo::CommonMessage_Type_LOGIN_REQUEST);
     oCommonMsg.set_value(oLoginRequest.SerializeAsString());

    string strCommonMsg = oCommonMsg.SerializeAsString();
    int nLen = google::protobuf::io::CodedOutputStream::VarintSize32(strCommonMsg.length());
   google::protobuf::uint8 *pLen = new google::protobuf::uint8[nLen];
   google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(strCommonMsg.length(), pLen);
   string st((const char *)pLen, nLen);
   st += strCommonMsg;
   delete [] pLen;
   SendTcpSocket(st.c_str(), st.size());



2. 把protoBuffer转换成  本地字符串。

google::protobuf::uint32 uiLength = 0;
   google::protobuf::io::CodedInputStream is((google::protobuf::uint8 *)pResvBuf, nRecvBytes); 
    is.ReadVarint32(&uiLength);
    char *pBuf = new char[uiLength];
    is.ReadRaw(pBuf, uiLength);
   duolabo::CommonMessage oCommonMsg;
   string strCommonMsg(pBuf, uiLength);
   delete [] pBuf;
if(oCommonMsg.ParseFromString(strCommonMsg))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值