简体   繁体   中英

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));         
                                              }

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, eg 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 aa 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM