开发者

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

开发者 https://www.devze.com 2023-02-27 10:35 出处:网络
I have some issue with boost::asio::async_read Here\'s my code void TCPConnection::listenForRead() { boost::asio::async_read(m_socket,

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 ?


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.


To go along with dauphic's answer:

You may initialize a char array like you did:

 char data[64]

Or if you still want to use a vector you can initialize the vector to a certain size:

std::vector<char> data(64)

           or

std::vector<char> data;
data.resize(64);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号