[英]boost::asio::async_read and boost::asio::streambuf
I am using async_read with streambuf. 我正在使用async_read与streambuf。 However, I would like to limit the amount of data read to 4, so I can properly handle header before going to body.
但是,我想将读取的数据量限制为4,因此我可以在处理正文之前正确处理标头。
How can I do that using async_read? 如何使用async_read做到这一点?
Use two async_read
operations where the first reads a 4 byte header, and the second reads the message body. 使用两个
async_read
操作,第一个读取一个4字节的标头,第二个读取消息的正文。 Your handler to the first async_read
should start the async_read
for the message body. 您对第一个
async_read
处理程序应启动消息正文的async_read
。
The asio examples use this technique in a couple of places, the serialization example is one. asio示例在很多地方都使用了这种技术, 序列化示例就是其中之一。 I also answered a similar question , though it uses synchronous reads, but the concept is the same.
我还回答了一个类似的问题 ,尽管它使用同步读取,但是概念是相同的。
You can guarantee the header is available using transfer_at_least as CompletionCondition on async_read . 您可以使用transfer_at_least作为async_read上的CompletionCondition来确保标题可用。
Any superfluous body data (or further headers) can be processed once you handle the initial header. 一旦处理了初始标头,就可以处理任何多余的正文数据(或其他标头)。
boost::asio::transfer_exactly(streambuf.size())
is what you need.just try using like this: 是您所需要的。只需尝试像这样使用:
boost::asio::async_read(socket_,
buf,boost::asio::transfer_exactly(size_),
boost::bind(callback,
boost::asio::placeholders::error));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.