简体   繁体   English

在C ++套接字编程中使用google protobuf序列化和反序列化消息

[英]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; Server.cpp做编码:字符串缓冲区;

           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 如何在客户端使用Google协议缓冲区对上述消息进行解码
  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. 您不仅应该发送protobuf消息,还可以在客户端对其进行解码。

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. 一种简单的解决方案是使用网络字节顺序在套接字buffer.size()的值作为4字节整数发送,然后发送缓冲区本身。

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 . 让我们表示结果值s The client must then preallocate a buffer of size s and read s bytes from the socket into it. 然后,客户端必须预分配大小为s的缓冲区,并从套接字向其中读取s个字节。 After that, just use MessageLite::ParseFromString to reconstruct your protobuf. 之后,只需使用MessageLite :: ParseFromString来重构您的protobuf。

See here for more info on protobuf message methods. 有关protobuf消息方法的更多信息,请参见此处

Also, this document discourages the usage of required : 另外, 文档不鼓励使用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; Google的一些工程师得出的结论是,使用必需的弊大于利。 they prefer to use only optional and repeated. 他们更喜欢只使用可选的和重复的。 However, this view is not universal. 但是,这种观点并不普遍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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