Created
September 4, 2011 07:50
-
-
Save snaewe/1192479 to your computer and use it in GitHub Desktop.
boost::asio - async read with timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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