简体   繁体   中英

Serialize and deserialize the message using google protobuf in socket programming in C++

Message format to send to server side as below :

package test;

message Test {
  required int32 id = 1;
  required string name = 2;
}

Server.cpp to do encoding : string buffer;

           test::Test original;
           original.set_id(0);
           original.set_name("original");

           original.AppendToString(&buffer);
           send(acceptfd,buffer.c_str(), buffer.size(),0);

By this send function it will send the data to client,i hope and i am not getting any error also for this particular code.

But my concern is like below:

  1. How to decode using Google Protocol buffer for the above message in the client side
  2. So that i can see/print the message.

You should send more than just the protobuf message to be able to decode it on the client side.

A simple solution would be to send the value of buffer.size() over the socket as a 4-byte integer using network byte order, and the send the buffer itself.

The client should first read the buffer's size from the socket and convert it from network to host byte order. Let's denote the resulting value s . The client must then preallocate a buffer of size s and read s bytes from the socket into it. After that, just use MessageLite::ParseFromString to reconstruct your protobuf.

See here for more info on protobuf message methods.

Also, this document discourages the usage of required :

You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that using required does more harm than good; they prefer to use only optional and repeated. However, this view is not universal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM