I am trying to implement a ConnectWithTimeout function for a boost socket. So I'm using one of the examples I found here. This works perfectly on this first try, but the io_service.run_one() returns immediately with a timeout or a cancel error.
Here is my code
using NetStatus = boost::system::error_code;
NetStatus handleWait(const NetStatus& error)
{
return boost::asio::error::timed_out;
}
NetStatus handleConnect(const NetStatus& error)
{
// The async_connect() function automatically opens the socket at the start
// of the asynchronous operation. If the socket is closed at this time then
// the timeout handler must have run first.
if (!m_socket.is_open())
return boost::asio::error::timed_out;
// Otherwise, a connection has been established. Update the timer state
// so that the timeout handler does not close the socket.
m_connectionTimeoutTimer.cancel();
return error;
}
void connectWithTimeout(boost::asio::ip::tcp::endpoint& endpoint, NetStatus& e)
{
// Stop last time's waiting objects
m_socket.cancel()
m_connectionTimeoutTimer.cancel();
m_ioService.stop();
m_ioService.reset();
// Set-up new objects to wait
m_connectionTimeoutTimer.expires_from_now(boost::posix_time::seconds(5));
m_connectionTimeoutTimer.async_wait([this, &e](const NetStatus& error) { e = handleWait(error); } );
m_socket.async_connect(endpoint, [this, &e](const NetStatus& error) { e = handleConnect(error); } );
// Block until one of them is done
m_ioService.run_one(e);
}
boost::asio::ip::tcp::socket m_socket;
boost::asio::deadline_timer m_connectionTimeoutTimer;
The results I'm seeing when running this in a loop are: Timeout (after 5 seconds as expected) Cancel (Immediately) Timeout (Immediately) Cancel (Immediately) Timeout (Immediately) Cancel (Immediately) Timeout (Immediately) ...
Can anyone please help spot what I'm doing wrong?