]>
Commit | Line | Data |
---|---|---|
11fdf7f2 TL |
1 | // |
2 | // refactored_echo_server.cpp | |
3 | // ~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
4 | // | |
f67539c2 | 5 | // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) |
11fdf7f2 TL |
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 | ||
92f5a8d4 TL |
11 | #include <boost/asio/co_spawn.hpp> |
12 | #include <boost/asio/detached.hpp> | |
11fdf7f2 TL |
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; | |
92f5a8d4 TL |
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; | |
11fdf7f2 TL |
25 | |
26 | awaitable<void> echo_once(tcp::socket& socket) | |
27 | { | |
11fdf7f2 | 28 | char data[128]; |
92f5a8d4 TL |
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); | |
11fdf7f2 TL |
31 | } |
32 | ||
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 | ||
52 | awaitable<void> listener() | |
53 | { | |
92f5a8d4 TL |
54 | auto executor = co_await this_coro::executor; |
55 | tcp::acceptor acceptor(executor, {tcp::v4(), 55555}); | |
11fdf7f2 TL |
56 | for (;;) |
57 | { | |
92f5a8d4 | 58 | tcp::socket socket = co_await acceptor.async_accept(use_awaitable); |
11fdf7f2 TL |
59 | co_spawn(executor, |
60 | [socket = std::move(socket)]() mutable | |
61 | { | |
62 | return echo(std::move(socket)); | |
63 | }, | |
64 | detached); | |
65 | } | |
66 | } | |
67 | ||
68 | int main() | |
69 | { | |
70 | try | |
71 | { | |
72 | boost::asio::io_context io_context(1); | |
73 | ||
74 | boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); | |
75 | signals.async_wait([&](auto, auto){ io_context.stop(); }); | |
76 | ||
77 | co_spawn(io_context, listener, detached); | |
78 | ||
79 | io_context.run(); | |
80 | } | |
81 | catch (std::exception& e) | |
82 | { | |
83 | std::printf("Exception: %s\n", e.what()); | |
84 | } | |
85 | } |