]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp17/coroutines_ts/double_buffered_echo_server.cpp
2 // double_buffered_echo_server.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2018 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/experimental/co_spawn.hpp>
12 #include <boost/asio/experimental/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::experimental::co_spawn
;
21 using boost::asio::experimental::detached
;
22 namespace this_coro
= boost::asio::experimental::this_coro
;
25 using awaitable
= boost::asio::experimental::awaitable
<
26 T
, boost::asio::io_context::executor_type
>;
28 awaitable
<void> echo(tcp::socket s
)
30 auto token
= co_await
this_coro::token();
40 // Perform initial read into first buffer.
41 size_t n
= co_await s
.async_read_some(boost::asio::buffer(p1
, 1024), token
);
45 // Swap received data to other buffer and initiate write operation.
47 auto write_result
= boost::asio::async_write(s
, boost::asio::buffer(p2
, n
), token
);
49 // Perform next read while write operation is in progress.
50 n
= co_await s
.async_read_some(boost::asio::buffer(p1
, 1024), token
);
52 // Wait for write operation to complete before proceeding.
53 co_await write_result
;
56 catch (std::exception
& e
)
58 std::printf("echo Exception: %s\n", e
.what());
62 awaitable
<void> listener()
64 auto executor
= co_await
this_coro::executor();
65 auto token
= co_await
this_coro::token();
67 tcp::acceptor
acceptor(executor
.context(), {tcp::v4(), 55555});
70 tcp::socket socket
= co_await acceptor
.async_accept(token
);
72 [socket
= std::move(socket
)]() mutable
74 return echo(std::move(socket
));
84 boost::asio::io_context
io_context(1);
86 boost::asio::signal_set
signals(io_context
, SIGINT
, SIGTERM
);
87 signals
.async_wait([&](auto, auto){ io_context
.stop(); });
89 co_spawn(io_context
, listener
, detached
);
93 catch (std::exception
& e
)
95 std::printf("Exception: %s\n", e
.what());