Converting (parsing) google protocol buffer streams from socket

馋奶兔 提交于 2019-12-11 23:12:45

问题


I am using the following code to parse a message that was SerializedwithCodedStream on to the socket:

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;
}

Here is how I serialized it:

    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;

When I try to parse, it gives the following error at runtime:

[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

But as you can see (in the second code snippet) I have set the type field. What is the problem ?


回答1:


You're ignoring the count returned by read(), other than checking it for -1. You need to use it instead of size when constructing array_input.



来源:https://stackoverflow.com/questions/25351713/converting-parsing-google-protocol-buffer-streams-from-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!