Search code examples
c++byteboost-asiolimit

Async_read_until limit size of bytes read (Boost::asio)


i want to know how can i limit the size of bytes to read with async_red_until . From now i used it with a delimter character but i want to change. Here is what i do :

void  Client::doRead()                                                                      
{                                                                                             
    boost::asio::async_read_until(m_socket,                                               
                                    m_buffer,                                             
                                    '\n',                                                 
                                  boost::bind(&Client::handleRead,                        
                                              shared_from_this(),                         
                                              boost::asio::placeholders::error));         
                                              }

Solution

  • You could use transfer_exactly (https://www.boost.org/doc/libs/1_68_0/doc/html/boost_asio/reference/transfer_exactly.html)

    Note that there is no guarantee you'll always read the amount, e.g. if the sending side closes the connection early. So check bytes_transferred as well as the error_code.

    In many cases you can simply use async_read instead, with a a fixed buffer:

    std::vector<char> m_buffer;
    
    // ...
    m_buffer.resize(24); // receive no more than 24 characters
    boost::asio::async_read(m_socket, 
              boost::asio::buffer(m_buffer),                                             
              boost::bind(&Client::handleRead, shared_from_this(),                                               
              boost::asio::placeholders::error));