"two stage" async_read with boost asio

I want to implement a protocol on top of a TCP / IP stack using boost asio. Protocol Length - PDU is contained in the 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 entire PDU.

I would rather use asynchronous methods, but while looking into example in the asio documentation I asked a question. The author is using the async_read_some () socket member function, which reads (apparently to me) an undefined amount of data from the socket. How do I apply my "two-step" procedure outlined in the first paragraph to get the complete PDU? Or is there another recommended solution for my problem?


+3


source to share


1 answer


Use non-member functions async_read

to read a fixed amount.

For example, using 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
                     }
                });
        }
    });

      

+4


source







All Articles