使用boost :: asio :: read_async读取Protobuf对象 [英] Reading Protobuf objects using boost::asio::read_async

查看:114
本文介绍了使用boost :: asio :: read_async读取Protobuf对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Boost asio编写应用程序,其中客户端和服务器交换使用Google原型缓冲区序列化的消息.我不知道通过网络发送的序列化消息的大小是多少.原始buf对象似乎没有任何定界符.

I am writing an application using Boost asio in which the client and the server exchange messages that are serialized using 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文件的内容.

Here are the contents of the .proto file.

 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));

在客户端中,我正在阅读上面使用boost :: asio :: async_read发送的消息.如何在下面的代码中找出arg的值设置为boost::asio::transfer_at_least的参数?

In the client I am reading the message sent above using 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?

 boost::asio::async_read(socket_, response_,
                            boost::asio::transfer_at_least(arg),
                            boost::bind(&Client::handle_read_header, this,
                                    boost::asio::placeholders::error));

否则,如何确保在读取整个对象后boost :: async_read返回?

Or else how do I make sure that boost::async_read returns after reading the entire object?

推荐答案

正确,protobuf没有定界.不知道消息从字节流的结尾处开始-即使您已经了解了所有已知字段,也许还有更多重复的元素,或者有人用未知字段扩展了原型.

Correct, protobufs are not delimited. 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.

常见的解决方案是为帧添加长度(通常编码为VarInt s). LevelDB

A common solution is to prefix frames with lengths (commonly encoded as VarInts). LevelDB and Szl both use this approach, for example. A VarInt can be unambiguously decoded byte by byte, and then you know how many more bytes to read before parsing your complete message.

这篇关于使用boost :: asio :: read_async读取Protobuf对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆