2012-07-24 8 views
12

che sto usando protobuf per serializzare messaggio che viene inviato su una connessione socket in C++. Per la comunicazione mi piacerebbe aggiungere un'intestazione ai messaggi che indicano la lunghezza del messaggio. Cosa ne pensi di questa implementazione? Ho fatto delle ricerche e questo è quello che ho messo insieme.Lunghezza prefisso per i messaggi protobuf in C++

Esiste un modo più bello per fare questo? Questa implementazione può causare problemi? So che esiste un supporto API per Java, ma sfortunatamente non per C++.

bool send_message(int socket, my_protobuf::Message message) 
{ 
    google::protobuf::uint32 message_length = message.ByteSize(); 
    int prefix_length = sizeof(message_length); 
    int buffer_length = prefix_length + message_length; 
    google::protobuf::uint8 buffer[buffer_length]; 

    google::protobuf::io::ArrayOutputStream array_output(buffer, buffer_length); 
    google::protobuf::io::CodedOutputStream coded_output(&array_output); 

    coded_output.WriteLittleEndian32(message_length); 
    message.SerializeToCodedStream(&coded_output); 

    int sent_bytes = write(socket, buffer, buffer_length); 
    if (sent_bytes != buffer_length) { 
    return false; 
    } 

    return true; 
} 

bool recv_message(int socket, my_protobuf::Message *message) 
{ 
    google::protobuf::uint32 message_length; 
    int prefix_length = sizeof(message_length); 
    google::protobuf::uint8 prefix[prefix_length]; 

    if (prefix_length != read(socket, prefix, prefix_length)) { 
    return false; 
    } 
    google::protobuf::io::CodedInputStream::ReadLittleEndian32FromArray(prefix, 
     &message_length); 

    google::protobuf::uint8 buffer[message_length]; 
    if (message_length != read(socket, buffer, message_length)) { 
    return false; 
    } 
    google::protobuf::io::ArrayInputStream array_input(buffer, message_length); 
    google::protobuf::io::CodedInputStream coded_input(&array_input); 

    if (!message->ParseFromCodedStream(&coded_input)) { 
    return false; 
    } 

    return true; 
} 
+1

vedere [risposta] (http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-io-functions-in-ja) – alavrik

+0

è necessario che il buffer sia di tipo int8 senza segno? – Chani

+0

In che modo il tuo socket-> write() accetta il buffer del tipo google :: protobuf :: uint8? – Chani

risposta

5

E 'più comune l'uso di varint (ad esempio WriteVarint32) piuttosto che fixed32 (dove si ha WriteLittleEndian32), ma la pratica di delimitare flussi protobuf anteponendo con la lunghezza è il suono.

Problemi correlati