Boost::asio async_read call 2 times

  asio, boost-asio, c++

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.

Source: Windows Questions C++

LEAVE A COMMENT