Note that there are some explanatory texts on larger screens.

plurals
  1. POBoost.Asio deadline_timer not working as expected
    primarykey
    data
    text
    <p>I'm trying to implement a timeout for a Boost.Asio read on a TCP socket.</p> <p>I am trying to use a <code>async_read_some</code> with a <code>deadline_timer</code>. My function below is a member of a class that holds a smart pointer to the TCP socket and <code>io_service</code>. What I would <strong>expect</strong> to happen when called on an active socket that doesn't return any data is <strong>wait 2 seconds and return false</strong>.</p> <p>What happens is: If the socket never returns any data it works as expected. How ever if the server returns the data the proceeding calls to the method below return immediately because to timers callback is called without waiting the two seconds.</p> <p>I tried commenting out the <code>async_read_some</code> call and the function always works as expected. Why would <code>async_read_some</code> change how the timer works?</p> <pre><code> client::client() { // Init socket and timer pSock = boost::shared_ptr&lt;tcp::socket &gt; (new tcp::socket(io_service)); } bool client::getData() { // Reset io_service io_service.reset(); // Init read timer boost::asio::deadline_timer timer(pSock-&gt;io_service()); timer.expires_from_now(boost::posix_time::seconds(2)); timer.async_wait(boost::bind(&amp;client::read_timeout, this, boost::system::error_code(), true)); // // Async read the data pSock-&gt;async_read_some(boost::asio::buffer(buffer_), boost::bind(&amp;client::read_complete, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred )); // While io_service runs check read result while (pSock-&gt;io_service().run_one()) { if (m_read_result &gt; 0) { // Read success return m_read_result; }else if(m_read_result &lt; 0){ return false; } } } } void client::read_complete(const boost::system::error_code&amp; error, size_t bytes_transferred) { if (!error) { m_read_result = bytes_transferred; }else{ m_read_result = -1; } } void client::read_timeout(const boost::system::error_code&amp; error, bool timeout) { if(!error){ m_read_result = -1; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload