]>
Commit | Line | Data |
---|---|---|
11fdf7f2 TL |
1 | // |
2 | // echo_server.cpp | |
3 | // ~~~~~~~~~~~~~~~ | |
4 | // | |
92f5a8d4 | 5 | // Copyright (c) 2003-2019 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(tcp::socket socket) | |
27 | { | |
11fdf7f2 TL |
28 | try |
29 | { | |
30 | char data[1024]; | |
31 | for (;;) | |
32 | { | |
92f5a8d4 TL |
33 | std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data), use_awaitable); |
34 | co_await async_write(socket, boost::asio::buffer(data, n), use_awaitable); | |
11fdf7f2 TL |
35 | } |
36 | } | |
37 | catch (std::exception& e) | |
38 | { | |
39 | std::printf("echo Exception: %s\n", e.what()); | |
40 | } | |
41 | } | |
42 | ||
43 | awaitable<void> listener() | |
44 | { | |
92f5a8d4 TL |
45 | auto executor = co_await this_coro::executor; |
46 | tcp::acceptor acceptor(executor, {tcp::v4(), 55555}); | |
11fdf7f2 TL |
47 | for (;;) |
48 | { | |
92f5a8d4 | 49 | tcp::socket socket = co_await acceptor.async_accept(use_awaitable); |
11fdf7f2 TL |
50 | co_spawn(executor, |
51 | [socket = std::move(socket)]() mutable | |
52 | { | |
53 | return echo(std::move(socket)); | |
54 | }, | |
55 | detached); | |
56 | } | |
57 | } | |
58 | ||
59 | int main() | |
60 | { | |
61 | try | |
62 | { | |
63 | boost::asio::io_context io_context(1); | |
64 | ||
65 | boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); | |
66 | signals.async_wait([&](auto, auto){ io_context.stop(); }); | |
67 | ||
68 | co_spawn(io_context, listener, detached); | |
69 | ||
70 | io_context.run(); | |
71 | } | |
72 | catch (std::exception& e) | |
73 | { | |
74 | std::printf("Exception: %s\n", e.what()); | |
75 | } | |
76 | } |