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

TL;DR socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 }); FULL ANSWER This question keep being asked over and over again for many years. Answers I saw so far are quite poor. I’ll add this info right here in one of the first occurrences of this question. Everybody trying to use ASIO to simplify their networking code would be perfectly … Read more

Best documentation for Boost:asio?

Some nice documentation on boost including a chapter on asio can be found in a (free) boost book at http://en.highscore.de/cpp/boost/index.html. The chapter on asio provides a general overview and then goes as far as how to develop your own custom asio extensions. Really fantastic effort by Boris Schäling!

Should the exception thrown by boost::asio::io_service::run() be caught?

Yes. It is documented that exceptions thrown from completion handlers are propagated. So you need to handle them as appropriate for your application. In many cases, this would be looping and repeating the run() until it exits without an error. In our code base I have something like static void m_asio_event_loop(boost::asio::io_service& svc, std::string name) { … Read more

Confused when boost::asio::io_service run method blocks/unblocks

Foundation Lets start with a simplified example and examine the relevant Boost.Asio pieces: void handle_async_receive(…) { … } void print() { … } … boost::asio::io_service io_service; boost::asio::ip::tcp::socket socket(io_service); … io_service.post(&print); // 1 socket.connect(endpoint); // 2 socket.async_receive(buffer, &handle_async_receive); // 3 io_service.post(&print); // 4 io_service.run(); // 5 What Is A Handler? A handler is nothing more than … Read more

boost asio async_write : how to not interleaving async_write calls?

Is there a simple way to avoid this problem ? Yes, maintain an outgoing queue for each client. Inspect the queue size in the async_write completion handler, if non-zero, start another async_write operation. Here is a sample #include <boost/asio.hpp> #include <boost/bind.hpp> #include <deque> #include <iostream> #include <string> class Connection { public: Connection( boost::asio::io_service& io_service ) … Read more

Why do I need strand per connection when using boost::asio?

The documentation is correct. With a half duplex protocol implementation, such as HTTP Server 3, the strand is not necessary. The call chains can be illustrated as follows: void connection::start() { socket.async_receive_from(…, &handle_read); —-. } | .————————————————‘ | .—————————————–. V V | void connection::handle_read(…) | { | if (result) | boost::asio::async_write(…, &handle_write); —|–. else if … Read more