[英]“two-step” async_read with boost asio
I want to implement a protocol on top of the TCP/IP stack using boost asio. 我想使用boost asio在TCP / IP堆栈之上实现协议。 The length of a protocol - PDU is contained in its first 6 bytes.
协议的长度 - PDU包含在前6个字节中。 Now using the synchronous read methods provided by asio, I can read exactly the first 6 bytes, calculate the length n and then read exactly n bytes to get the whole PDU.
现在使用asio提供的同步读取方法,我可以准确读取前6个字节,计算长度n然后读取n个字节以获得整个PDU。
I would rather use the asynchronous methods, though, but studying the example in the asio documentation leaves me with a question. 我宁愿使用异步方法,但是在asio文档中研究这个例子给我留下了一个问题。 The author uses the socket member function async_read_some(), which reads an (seemingly for me) indeterminate amount of data from the socket.
作者使用套接字成员函数async_read_some(),它从套接字中读取(看似对我而言)不确定数量的数据。 How would I apply my "two-step" procedure described in the first paragraph to receive the complete PDU?
我如何应用第一段中描述的“两步”程序来接收完整的PDU? Or is there another advisable solution for my problem?
或者我的问题还有另一个明智的解决方案吗?
Use the non-member functions async_read
to read a fixed amount. 使用非成员函数
async_read
读取固定数量。
For example, using a std::vector
or similar for a buffer: 例如,使用
std::vector
或类似的缓冲区:
// read the header
buffer.resize(6);
async_read(socket, boost::asio::buffer(buffer),
[=](const boost::system::error_code & error, size_t bytes){
if (!error) {
assert(bytes == 6);
// read the payload
buffer.resize(read_size(buffer));
async_read(socket, boost::asio::buffer(buffer),
[=](const boost::system::error_code & error, size_t bytes){
if (!error) {
// process the payload
}
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.