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