test/ttimeout.cc
/**
 * Read a line from the socket into a string, WITH a timeout.
 * Ref: https://stackoverflow.com/questions/13126776/asioread-with-timeout
 * N.b.: This will only work reliably in a *single-threaded* context.
 * Replaced calls to get_io_service() with get_executor() for boost 1.70+
 */
Read a line from the socket into a string, WITH a timeout.
Read a line from the socket into a string WITH a timeout .
void tclient::readWithTimeout( std::string& result_line,
          const boost::asio::deadline_timer::duration_type& expiry_time)
{
    boost::optional<boost::system::error_code> timer_result;
    boost::asio::deadline_timer timer( m_io_service );
    timer.expires_from_now(expiry_time);
    timer.async_wait([&timer_result]
                     (const boost::system::error_code& error) {
                         timer_result.reset(error); });
    boost::asio::streambuf data;
    boost::optional<boost::system::error_code> read_result;
    boost::asio::async_read_until( m_socket, data, '\n',
           [&read_result,&result_line,&data]
           (const boost::system::error_code& error, size_t)
           {
               if (!error) {
                   std::istream instr(&data);
                   std::getline(instr, result_line);
               }
               read_result.reset(error);
           });
    m_io_service.reset();
    while (m_io_service.run_one())
    {
        if (read_result)
            timer.cancel();
        else if (timer_result)
            m_socket.cancel();
    }
    if (*read_result) {
        throw boost::system::system_error(*read_result);
    }
}
void tclient :: readWithTimeout ( std :: string & result_line , const boost :: asio :: deadline_timer :: duration_type & expiry_time ) { boost :: optional < boost :: system :: error_code > timer_result ; boost :: asio :: deadline_timer timer ( m_io_service ) ; timer . expires_from_now ( expiry_time ) ; timer . async_wait ( [ & timer_result ] ( const boost :: system :: error_code & error ) { timer_result . reset ( error ) ; } ) ; boost :: asio :: streambuf data ; boost :: optional < boost :: system :: error_code > read_result ; boost :: asio :: async_read_until ( m_socket , data , ' \n ' , [ & read_result , & result_line , & data ] ( const boost :: system :: error_code & error , size_t ) { if ( ! error ) { std :: istream instr ( & data ) ; std :: getline ( instr , result_line ) ; } read_result . reset ( error ) ; } ) ; m_io_service . reset ( ) ; while ( m_io_service . run_one ( ) ) { if ( read_result ) timer . cancel ( ) ; else if ( timer_result ) m_socket . cancel ( ) ; } if ( * read_result ) { throw boost :: system :: system_error ( * read_result ) ; } }
Read a line from the socket into a string, WITH a timeout.
Read a line from the socket into a string WITH a timeout .
//