![]() |
Home | Libraries | People | FAQ | More |
In this tutorial we will rewrite the synchronous TCP daytime client from tutorial Daytime.1 as a coroutine, and add timeouts so that the client does not wait forever for a server that fails to respond. This tutorial program requires a compiler that supports C++20 coroutines.
#include <array> #include <exception> #include <iostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp;
The work of the client is done by a coroutine called get_daytime(), which is given the name of the server.
We obtain the executor that the coroutine is running on, which we will use
to construct the I/O objects.
boost::asio::awaitable<void> get_daytime(std::string host) { auto executor = co_await boost::asio::this_coro::executor;
As in tutorial Daytime.1, we use an ip::tcp::resolver object to turn the server name into a list of endpoints. This time the coroutine waits for ip::tcp::resolver::async_resolve() to complete.
tcp::resolver resolver(executor); tcp::resolver::results_type endpoints = co_await resolver.async_resolve(host, "daytime");
Next we create and connect the socket. The boost::asio::async_connect() function tries each endpoint in turn, just as boost::asio::connect() did.
We supply the boost::asio::cancel_after completion token adapter, which adds
a timeout to the operation. If the connection has not been established within
10 seconds, the operation is cancelled and fails with the boost::asio::error::operation_aborted
error. We have not given boost::asio::cancel_after a completion token to
wrap, so it uses the operation's default completion token, boost::asio::deferred.
The coroutine can still wait for the result using co_await.
tcp::socket socket(executor); co_await boost::asio::async_connect(socket, endpoints, boost::asio::cancel_after(boost::asio::chrono::seconds(10)));
Since an operation called without a completion token returns a deferred operation, the same thing can also be written using the pipe operator:
co_await (boost::asio::async_connect(socket, endpoints) | boost::asio::cancel_after(boost::asio::chrono::seconds(10)));
The pipe operator passes the completion token on its right to the deferred
operation on its left. The parentheses are required because co_await binds more tightly than the pipe
operator.
The timeout's wait runs in parallel with the operation, so boost::asio::cancel_after requires the operation to be performed within an implicit or explicit strand. Calling boost::asio::io_context::run() from only one thread, as this program does, provides an implicit strand.
The connection is open. All we need to do now is read the response from the daytime service. Each read is given its own 10 second timeout.
try { for (;;) { std::array<char, 128> buf; size_t len = co_await socket.async_read_some(boost::asio::buffer(buf), boost::asio::cancel_after(boost::asio::chrono::seconds(10))); std::cout.write(buf.data(), len); } }
When the server closes the connection, the read fails with the boost::asio::error::eof error. In a coroutine this error is thrown as an exception, which is how the loop ends. We catch the exception and rethrow any other error, such as the boost::asio::error::operation_aborted error from a read that has timed out.
catch (boost::system::system_error& e) { if (e.code() != boost::asio::error::eof) throw; // Some other error. } }
The main function checks
the command line arguments and creates the io_context
object, as in tutorial Daytime.1.
int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: client <host>" << std::endl; return 1; } boost::asio::io_context io_context;
We start the coroutine using boost::asio::co_spawn(), with the same completion handler as in tutorial Daytime.8. If the coroutine ends with an exception, it is rethrown from boost::asio::io_context::run().
boost::asio::co_spawn(io_context, get_daytime(argv[1]), [](std::exception_ptr e) { if (e) std::rethrow_exception(e); }); io_context.run();
Finally, handle any exceptions that may have been thrown.
} catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
See the full source listing
Return to the tutorial index
Previous: Daytime.8 - An asynchronous TCP daytime server using coroutines
Next: Daytime.10 - An asynchronous TCP daytime client using as_tuple