使用boost :: asio :: read_async读取Protobuf对象

san*_*ank 6 c++ protocol-buffers boost-asio

我正在使用Boost asio编写一个应用程序,其中客户端和服务器交换使用google proto-buffers序列化的消息.我不知道通过网络发送的序列化消息的大小是多少.似乎proto-buf对象没有任何分隔符.

以下是.proto文件的内容.

 package tutorial;

message Person {
        required string name = 1;
        required int32 id = 2;
        optional string email = 3;
}
Run Code Online (Sandbox Code Playgroud)

这是我从服务器写的方式

        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));
Run Code Online (Sandbox Code Playgroud)

在客户端我正在使用boost :: asio :: async_read读取上面发送的消息.如何在下面的代码中找出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));
Run Code Online (Sandbox Code Playgroud)

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

eph*_*ent 6

正确的,protobufs没有分隔.不知道消息从字节流到哪里结束 - 即使你已经看到了你所知道的所有字段,也许有更多的重复元素,或者有人用你不知道的字段扩展了原型.

常见的解决方案是为帧添加长度(通常编码为VarInts). 例如,LevelDBSzl都使用这种方法.A VarInt可以逐字节地明确解码,然后在解析完整的消息之前知道要读取多少字节.

  • 另请参阅http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-io-functions-in-ja某些API具有分隔的书写/阅读功能,您可以轻松地如答案中所述,为自己实施. (2认同)