[英]Reading Protobuf objects using boost::asio::read_async
I am writing an application using Boost asio in which the client and the server exchange messages that are serialized using google proto-buffers. 我正在使用Boost asio编写一个应用程序,其中客户端和服务器交换使用google proto-buffers序列化的消息。 I do not know what is the size of the serialized message being sent on over the network.
我不知道通过网络发送的序列化消息的大小是多少。 It seems that the proto-buf objects do not have any delimiter.
似乎proto-buf对象没有任何分隔符。
Here are the contents of the .proto file. 以下是.proto文件的内容。
package tutorial;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
Here is how I am writing from the server 这是我从服务器写的方式
tutorial::Person p;
p.set_name("abcd pqrs");
p.set_id(123456);
p.set_email("abcdpqrs@gmail.com");
write(p);
boost::asio::streambuf b;
std::ostream os(&b);
p.SerializeToOstream(&os);
boost::asio::async_write(socket_, b,
boost::bind(&Server::handle_write, this,
boost::asio::placeholders::error));
In the client I am reading the message sent above using boost::asio::async_read. 在客户端我正在使用boost :: asio :: async_read读取上面发送的消息。 How do I find out the value of
arg
be set as an argument to boost::asio::transfer_at_least
, in the code below? 如何在下面的代码中找出
arg
的值被设置为boost::asio::transfer_at_least
的参数?
boost::asio::async_read(socket_, response_,
boost::asio::transfer_at_least(arg),
boost::bind(&Client::handle_read_header, this,
boost::asio::placeholders::error));
Or else how do I make sure that boost::async_read returns after reading the entire object? 或者,如何在读取整个对象后确保boost :: async_read返回?
Correct, protobufs are not delimited. 正确的,protobufs没有分隔。 There's no knowing where a message ends from just a bytestream — even if you've seen all the fields you know about, maybe there are more repeated elements or somebody has extended the proto with a field you don't know about.
不知道消息从字节流到哪里结束 - 即使你已经看到了你所知道的所有字段,也许有更多的重复元素,或者有人用你不知道的字段扩展了原型。
A common solution is to prefix frames with lengths (commonly encoded as VarInt
s). 常见的解决方案是为帧添加长度(通常编码为
VarInt
)。 LevelDB and Szl both use this approach, for example. 例如,LevelDB和Szl都使用这种方法。 A
VarInt
can be unambiguously decoded byte by byte, and then you know how many more bytes to read before parsing your complete message. 可以逐字节地明确解码
VarInt
,然后在解析完整的消息之前知道要读取多少字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.