Boost::asio async_read call 2 times

Viewed 165

i try to call async_read function 2 times because i want to get header and calculate data size after that get data according to calculated size but handler is called 1 time by async_read function.

Article said that handler call when buffer was full or error occured. I check buffer and is full but handler is not called second time.

int calculateSize(uint8_t Header[]) {

    if (Header[2] == 0)
        return Header[3]-4;
    return (Header[2] * 256 + Header[3])-4;

}

void read_handler(
    const boost::system::error_code& ec,
    std::size_t bytes_transferred)
{
    if (ec) {
        cout << ec.message() << endl;
    }
    else
    {
        cout <<"Bytes received "<< bytes_transferred << endl;
    }
}

int receive_packet(Tcp_connection* connection) {
    int len = 0;
    uint8_t Header[4];

    async_read(*connection->sock, boost::asio::buffer(Header, sizeof(Header)),
        boost::bind(&read_handler,connection->ec,boost::asio::placeholders::bytes_transferred));
    connection->io_service->run();

    int dataSize = calculateSize(Header);
    uint8_t* Data = new uint8_t[dataSize];

        async_read(*connection->sock, boost::asio::buffer(Data, dataSize),
            boost::bind(&read_handler, connection->ec, boost::asio::placeholders::bytes_transferred));
        connection->io_service->run();
}

I want to use async_read for project future.

1 Answers

From the code I see that you want to read 4 bytes first, following read of N bytes.

In short, you need to schedule next read in a callback of the first read.

You should do something like this:

// schedule read of a header
async_read(*connection->sock, boost::asio::buffer(Header, sizeof(Header)),
        [](...){
  // handler N1
  read_handler(...);
  
  // schedule read of second part
  async_read(*connection->sock, boost::asio::buffer(Data, dataSize),
            [](...){
    // handler N2
    read_handler(...);
  });
 
});
    

This is called "callback hell" by the way, remember it when you want to chain async operations.

Related