Skip to content

Instantly share code, notes, and snippets.

@snaewe
Created September 4, 2011 07:50
Show Gist options
  • Save snaewe/1192479 to your computer and use it in GitHub Desktop.
Save snaewe/1192479 to your computer and use it in GitHub Desktop.
boost::asio - async read with timeout
void set_result(optional<error_code>* a, error_code b)
{
a->reset(b);
}
template <typename MutableBufferSequence>
void read_with_timeout(tcp::socket& sock,
const MutableBufferSequence& buffers)
{
optional<error_code> timer_result;
deadline_timer timer(sock.io_service());
timer.expires_from_now(seconds(1));
timer.async_wait(boost::bind(set_result, &timer_result, _1));
optional<error_code> read_result;
async_read(sock, buffers,
boost::bind(set_result, &read_result, _1));
sock.io_service().reset();
while (sock.io_service().run_one())
{
if (read_result)
timer.cancel();
else if (timer_result)
sock.cancel();
}
if (*read_result)
throw system_error(*read_result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment