]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp17/coroutines_ts/refactored_echo_server.cpp
2 // refactored_echo_server.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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)
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>
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
;
26 awaitable
<void> echo_once(tcp::socket
& socket
)
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
);
33 awaitable
<void> echo(tcp::socket socket
)
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
);
46 catch (std::exception
& e
)
48 std::printf("echo Exception: %s\n", e
.what());
52 awaitable
<void> listener()
54 auto executor
= co_await
this_coro::executor
;
55 tcp::acceptor
acceptor(executor
, {tcp::v4(), 55555});
58 tcp::socket socket
= co_await acceptor
.async_accept(use_awaitable
);
59 co_spawn(executor
, echo(std::move(socket
)), detached
);
67 boost::asio::io_context
io_context(1);
69 boost::asio::signal_set
signals(io_context
, SIGINT
, SIGTERM
);
70 signals
.async_wait([&](auto, auto){ io_context
.stop(); });
72 co_spawn(io_context
, listener(), detached
);
76 catch (std::exception
& e
)
78 std::printf("Exception: %s\n", e
.what());