Ejemplo n.º 1
0
std::string CTcpCode::Encode(const google::protobuf::Message& message)
{
    std::string result;    
    result.resize(PKGHEAD_FIELD_SIZE); //  预留消息头的前四个字节

    // 添加消息类型长度和消息类型具体内容
    const std::string& type_name = message.GetTypeName();
    int name_len = static_cast<int>(type_name.size()+1);
    int be32 = ::htonl(name_len);
    result.append(reinterpret_cast<char*>(&be32), sizeof(be32));
    result.append(type_name.c_str(), name_len);

    // 将protobuf message协议数据添加至result中
    bool succeed = message.AppendToString(&result);
    if(succeed)
    {
        // 计算消息体总长度值,并添加至消息头顶部
        int len = ::htonl(result.size());
        std::copy(reinterpret_cast<char*>(&len), reinterpret_cast<char*>(&len) + sizeof(len), result.begin());
        DLOG(INFO) << "encode message ok, name=" << type_name.c_str() << ", len=" << len;
    }
    else
    {
        LOG(ERROR) << "encode message error, name=" << type_name.c_str();
        result.clear();        
    }

    return result;
}
Ejemplo n.º 2
0
		static void FillBuffer(std::string &buf, const google::protobuf::Message& message)
		{
			typedef google::protobuf::int32 int32;

			const std::string& typeName = message.GetTypeName();
			int32 nameLen = static_cast<int32>(typeName.size()+1);
			int32 be32 = nameLen;

			buf.resize(sizeof(int32) * 2 + nameLen);

			buf.append(reinterpret_cast<char*>(&be32), sizeof be32);
			buf.append(typeName.c_str(), nameLen);
			bool succeed = message.AppendToString(&buf);

			if (succeed)
			{
				const char* begin = buf.c_str() + kHeaderLen;

				// CRC32 or adler32 ??
				int32 checkSum = 0;//adler32(1, reinterpret_cast<const Bytef*>(begin), result.size()-kHeaderLen);
				int32 be32 = checkSum;
				buf.append(reinterpret_cast<char*>(&be32), sizeof(be32));

				int32 len = buf.size() - kHeaderLen;
				int32 &totalLen = *(int32 *)(buf.data());
				totalLen = len;
			}
			else
			{
				buf.clear();
			}
		}