I want to implement a protocol on top of the TCP/IP stack using boost asio. The length of a protocol - PDU is contained in its first 6 bytes. 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.
I would rather use the asynchronous methods, though, but studying the example in the asio documentation leaves me with a question. The author uses the socket member function async_read_some(), which reads an (seemingly for me) indeterminate amount of data from the socket. How would I apply my "two-step" procedure described in the first paragraph to receive the complete PDU? Or is there another advisable solution for my problem?
Use the non-member functions async_read
to read a fixed amount.
For example, using a std::vector
or similar for a buffer:
// 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
}
});
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments