简体   繁体   中英

“two-step” async_read with boost asio

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
                     }
                });
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM