最近要求使用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());
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))
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))