]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp17/coroutines_ts/echo_server.cpp
update ceph source to reef 18.1.2
[ceph.git] / ceph / src / boost / libs / asio / example / cpp17 / coroutines_ts / echo_server.cpp
1 //
2 // echo_server.cpp
3 // ~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2022 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
26 #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING)
27 # define use_awaitable \
28 boost::asio::use_awaitable_t(__FILE__, __LINE__, __PRETTY_FUNCTION__)
29 #endif
30
31 awaitable<void> echo(tcp::socket socket)
32 {
33 try
34 {
35 char data[1024];
36 for (;;)
37 {
38 std::size_t n = co_await socket.async_read_some(boost::asio::buffer(data), use_awaitable);
39 co_await async_write(socket, boost::asio::buffer(data, n), use_awaitable);
40 }
41 }
42 catch (std::exception& e)
43 {
44 std::printf("echo Exception: %s\n", e.what());
45 }
46 }
47
48 awaitable<void> listener()
49 {
50 auto executor = co_await this_coro::executor;
51 tcp::acceptor acceptor(executor, {tcp::v4(), 55555});
52 for (;;)
53 {
54 tcp::socket socket = co_await acceptor.async_accept(use_awaitable);
55 co_spawn(executor, echo(std::move(socket)), 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 }