How to set a timeout on blocking sockets in boost asio?

Brian R. Bondy picture Brian R. Bondy · Nov 15, 2008 · Viewed 48.4k times · Source

Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions?

I.e. I want to set a timeout on blocking socket in boost asio?

socket.read_some(boost::asio::buffer(pData, maxSize), error_);

Example: I want to read some from the socket, but I want to throw an error if 10 seconds have passed.

Answer

William Symionow picture William Symionow · Dec 28, 2012

When this question was asked, I guess ASIO did not have any example on how to accomplish what the OP needed, that is to timeout a blocking operation such as a blocking socket operation. Now there exists examples to show you exactly how to do this. the example seems long, but that is because it is WELL commented. It shows how to use the ioservice in a 'one shot' kind of mode.

I think the example is a great solution. The other solutions here break portability and don't take advantage of ioservice. if portability is not important and the ioservice seems like to much overhead --THEN-- you should not be using ASIO. No matter what, you will have an ioservice created (almost all ASIO functionality depends on it, even sync sockets) so, take advantage of it.

Timeout a blocking asio tcp operation

Timeout a blocking asio udp operation

The ASIO documentation has been updated, so check it out for new examples on how to overcome some of the 'gotchas' ASIO use to have.