![]() |
Home | Libraries | People | FAQ | More |
In this tutorial we will rewrite the asynchronous TCP daytime server from tutorial Daytime.3 using coroutines. This tutorial program requires a compiler that supports C++20 coroutines.
#include <ctime> #include <exception> #include <iostream> #include <string> #include <utility> #include <boost/asio.hpp> using boost::asio::ip::tcp;
We use the same make_daytime_string() function as before to create the string
to be sent back to the client.
std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); }
The serve()
coroutine takes the place of the tcp_connection
class. It is given the socket for a newly accepted connection. The socket
is passed by value so that the coroutine owns it. A reference would not remain
valid while the coroutine is suspended.
boost::asio::awaitable<void> serve(tcp::socket socket) {
In tutorial Daytime.3 the data to be sent was stored in the class member
message_, because it had
to remain valid until the asynchronous operation was complete. A local variable
is now enough, since the coroutine's local variables are kept alive while
it is suspended.
std::string message = make_daytime_string();
We call boost::asio::async_write(), rather than ip::tcp::socket::async_write_some(),
to ensure that the entire block of data is sent. We omit the completion token,
so boost::asio::async_write() returns a deferred operation, and we wait for
it using co_await.
co_await boost::asio::async_write(socket, boost::asio::buffer(message)); }
Once the write has finished, the coroutine returns, and the socket is closed
when it is destroyed. You will notice that there is no need for shared_ptr or enable_shared_from_this.
The listener()
coroutine takes the place of the tcp_server
class. It uses the coroutine's executor to construct an acceptor that listens
on TCP port 13.
boost::asio::awaitable<void> listener() { auto executor = co_await boost::asio::this_coro::executor; tcp::acceptor acceptor(executor, tcp::endpoint(tcp::v4(), 13));
The start_accept()
and handle_accept()
functions from tutorial Daytime.3 become a single loop. Each time around
the loop, the coroutine waits for a new connection. When ip::tcp::acceptor::async_accept()
is called without a socket argument, it delivers the new socket as the result
of the operation.
for (;;) { tcp::socket socket = co_await acceptor.async_accept();
We then call boost::asio::co_spawn() to start a new coroutine that serves the client. The socket is moved into the new coroutine, and the listener goes straight back to accepting the next connection. We are not interested in the result, so we pass boost::asio::detached.
boost::asio::co_spawn(executor, serve(std::move(socket)), boost::asio::detached); } }
The main function begins
by creating the io_context
object.
int main() { try { boost::asio::io_context io_context;
We start the listener using boost::asio::co_spawn(). This time we pass a
completion handler, so that an error in the listener is not silently discarded.
If the coroutine ends with an exception, the handler rethrows it. The exception
then propagates out of boost::asio::io_context::run() and is caught in main.
boost::asio::co_spawn(io_context, listener(), [](std::exception_ptr e) { if (e) std::rethrow_exception(e); });
Run the io_context object so that it will perform asynchronous operations on your behalf.
io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
See the full source listing
Return to the tutorial index
Previous: Daytime.7 - A combined TCP/UDP asynchronous server
Next: Daytime.9 - An asynchronous TCP daytime client with timeouts