• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // refactored_echo_server.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6 //
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 //
10 
11 #include <boost/asio/co_spawn.hpp>
12 #include <boost/asio/detached.hpp>
13 #include <boost/asio/io_context.hpp>
14 #include <boost/asio/ip/tcp.hpp>
15 #include <boost/asio/signal_set.hpp>
16 #include <boost/asio/write.hpp>
17 #include <cstdio>
18 
19 using boost::asio::ip::tcp;
20 using boost::asio::awaitable;
21 using boost::asio::co_spawn;
22 using boost::asio::detached;
23 using boost::asio::use_awaitable;
24 namespace this_coro = boost::asio::this_coro;
25 
echo_once(tcp::socket & socket)26 awaitable<void> echo_once(tcp::socket& socket)
27 {
28   char data[128];
29   std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data), use_awaitable);
30   co_await async_write(socket, boost::asio::buffer(data, n), use_awaitable);
31 }
32 
echo(tcp::socket socket)33 awaitable<void> echo(tcp::socket socket)
34 {
35   try
36   {
37     for (;;)
38     {
39       // The asynchronous operations to echo a single chunk of data have been
40       // refactored into a separate function. When this function is called, the
41       // operations are still performed in the context of the current
42       // coroutine, and the behaviour is functionally equivalent.
43       co_await echo_once(socket);
44     }
45   }
46   catch (std::exception& e)
47   {
48     std::printf("echo Exception: %s\n", e.what());
49   }
50 }
51 
listener()52 awaitable<void> listener()
53 {
54   auto executor = co_await this_coro::executor;
55   tcp::acceptor acceptor(executor, {tcp::v4(), 55555});
56   for (;;)
57   {
58     tcp::socket socket = co_await acceptor.async_accept(use_awaitable);
59     co_spawn(executor, echo(std::move(socket)), detached);
60   }
61 }
62 
main()63 int main()
64 {
65   try
66   {
67     boost::asio::io_context io_context(1);
68 
69     boost::asio::signal_set signals(io_context, SIGINT, SIGTERM);
70     signals.async_wait([&](auto, auto){ io_context.stop(); });
71 
72     co_spawn(io_context, listener(), detached);
73 
74     io_context.run();
75   }
76   catch (std::exception& e)
77   {
78     std::printf("Exception: %s\n", e.what());
79   }
80 }
81