簡體   English   中英

在C ++中解析協議緩沖區

[英]Parsing protocol buffers in c++

我想將一些協議緩沖區寫入套接字,然后從客戶端讀取回去。 事情沒有進行,所以我在對服務器進行編碼后立即在服務器本身中編寫了一些解碼部分。 您能否看一下下面的代碼,然后告訴我我做錯了什么?

(我必須使用arraystream和編碼流,以便可以編寫定界符)

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

tData.SerializeToCodedStream(coded_output);

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

delete coded_output;



////////////////


google::protobuf::uint8 __buffer[sizeof(google::protobuf::uint32)];
memset(__buffer, '\0', sizeof(google::protobuf::uint32));
memcpy (__buffer, buffer, sizeof(google::protobuf::uint32));

google::protobuf::uint32 __size = 0;

google::protobuf::io::ArrayInputStream ais(__buffer,sizeof(google::protobuf::uint32));
google::protobuf::io::CodedInputStream coded_input(&ais);
coded_input. ReadVarint32(&__size);
std::cout <<" size of payload is "<<__size << std::endl;

google::protobuf::uint8 databuffer[__size];
memset(databuffer, '\0', __size);
memcpy (databuffer, buffer+sizeof(google::protobuf::uint32), __size);    

std::cout << "databuffs " << "size " << __size << "  "<< databuffer << std::endl;
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))
{
    std::cout << "data could not be parsed" << std::endl;     
}
else
{
    std::cout <<" SYMBOL --" << tData->symbol_name() << std::endl;
}
delete tData;

程序輸出:

size of payload is 55
databuffs size 55  C109"056*    BANKNIFTY0���20140915@�J    145406340
data could not be parsed
C109"056*   BANKNIFTY0���20140915@�J    145406340

WriteVarint32不一定要寫入4個字節,而ReadVarint32不必讀取4個字節。 如“可變長度編碼”中一樣,“ Var”代表“變量”。

編碼時,您寫出大小(可能只有一個字節),然后寫出原型。 解碼時,您讀取大小,然后前進四個字節,然后讀取原型。 因此,您是從錯誤的偏移量開始解析。

ReadVarint32之后使用CurrentPosition()來計算大小指示器消耗了多少字節。 前進該字節數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM