Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost::asio::async_read doesn't stop on condition

I have some issue with boost::asio::async_read

Here's my code

void TCPConnection::listenForRead() {

    boost::asio::async_read(m_socket, 
                            boost::asio::buffer(m_inbound_data),
                            boost::asio::transfer_at_least(64),
                            boost::bind(&TCPConnection::handle_read, 
                                        shared_from_this(),
                                        boost::asio::placeholders::error)
                            );
}

And Here's the handler :

void TCPConnection::handle_read(const boost::system::error_code& error) {
    if (error) {
        std::cout << "Error read: " << error.category().name() << " -- " << error.value() << std::endl;
    } else {

        std::string archive_data(&m_inbound_data[0], m_inbound_data.size()); 

        std::cout << "Message received: " << archive_data << std::endl;
        listenForRead();
    }
}

With

std::vector<char> m_inbound_data;

I get an infinite loop on the console when a client connect:

"Message received: " //no trace of message

If i print the data length, it is always at 0.

I connect with : telnet localhost 4242

Anyone know why ? should it not wait for at least 64 char ?

like image 816
TheSquad Avatar asked Jan 25 '26 08:01

TheSquad


1 Answers

Boost.Asio will never resize your buffer.

When you create a buffer from an std::vector<char>, the size of the buffer is the size of the vector.

If you don't give it a size, it will be a zero-length buffer.

The transfer_at_least functor returns true if either at least N bytes are in the buffer or the buffer is full. In the case of a zero length buffer, it's always full, so it always returns true.

like image 57
Collin Dauphinee Avatar answered Jan 27 '26 00:01

Collin Dauphinee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!