从套接字转换(解析)谷歌协议缓冲流

时间:2014-08-17 17:25:28

标签: c++ sockets networking protocol-buffers

我使用以下代码将SerializedwithCodedStream的消息解析为套接字:

if ( socket->read(databuffer, size) != -1)
{
    google::protobuf::io::ArrayInputStream array_input(databuffer,size);
    google::protobuf::io::CodedInputStream coded_input(&array_input);
    data_model::terminal_data* tData = new data_model::terminal_data();
    if (!tData->ParseFromCodedStream(&coded_input))
    {
        return;
    }
    else
    std::cout << tData->symbol_name() << std::endl;
}

以下是我如何序列化它:

    data_model::terminal_data tData;
    tData.set_type(1);
    tData.set_client_id("C109");
    tData.set_expiry("20140915");
    tData.set_quantity(3500);
    tData.set_strat_id("056");
    tData.set_symbol_name("BANKNIFTY");
    tData.set_time("145406340");
    tData.set_trade_id(16109234);

    int total_size = tData.ByteSize() + sizeof(int);
            char *buffer = new char[total_size];
            memset(buffer, '\0', total_size);
            google::protobuf::io::ArrayOutputStream aos(buffer,total_size);
            google::protobuf::io::CodedOutputStream *coded_output = new google::protobuf::io::CodedOutputStream(&aos);
            google::protobuf::uint32 s  = tData.ByteSize();
            coded_output->WriteVarint32(s);

            tData.SerializeToCodedStream(coded_output);

            int sent_bytes = 0;
            if ( (sent_bytes = send(liveConnections.at(i), buffer, total_size, MSG_NOSIGNAL)) == -1 )
                liveConnections.erase(liveConnections.begin() + i);
            else
                std::cout << "sent "  << sent_bytes << " bytes to " << i << std::endl;

            delete coded_output;
            delete buffer;

当我尝试解析时,它在运行时会出现以下错误:

[libprotobuf ERROR google/protobuf/message_lite.cc:123] Can't parse message of type "data_model.terminal_data" because it is missing required fields: type

但是你可以看到(在第二个代码片段中)我已经设置了类型字段。有什么问题?

1 个答案:

答案 0 :(得分:3)

您忽略read()返回的计数,而不是检查-1。在构建size时,您需要使用它而不是array_input