]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp17/coroutines_ts/double_buffered_echo_server.cpp
Add patch for failing prerm scripts
[ceph.git] / ceph / src / boost / libs / asio / example / cpp17 / coroutines_ts / double_buffered_echo_server.cpp
1 //
2 // double_buffered_echo_server.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2018 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/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>
17 #include <cstdio>
18
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;
23
24 template <typename T>
25 using awaitable = boost::asio::experimental::awaitable<
26 T, boost::asio::io_context::executor_type>;
27
28 awaitable<void> echo(tcp::socket s)
29 {
30 auto token = co_await this_coro::token();
31
32 try
33 {
34 char data1[1024];
35 char data2[1024];
36
37 char* p1 = data1;
38 char* p2 = data2;
39
40 // Perform initial read into first buffer.
41 size_t n = co_await s.async_read_some(boost::asio::buffer(p1, 1024), token);
42
43 for (;;)
44 {
45 // Swap received data to other buffer and initiate write operation.
46 std::swap(p1, p2);
47 auto write_result = boost::asio::async_write(s, boost::asio::buffer(p2, n), token);
48
49 // Perform next read while write operation is in progress.
50 n = co_await s.async_read_some(boost::asio::buffer(p1, 1024), token);
51
52 // Wait for write operation to complete before proceeding.
53 co_await write_result;
54 }
55 }
56 catch (std::exception& e)
57 {
58 std::printf("echo Exception: %s\n", e.what());
59 }
60 }
61
62 awaitable<void> listener()
63 {
64 auto executor = co_await this_coro::executor();
65 auto token = co_await this_coro::token();
66
67 tcp::acceptor acceptor(executor.context(), {tcp::v4(), 55555});
68 for (;;)
69 {
70 tcp::socket socket = co_await acceptor.async_accept(token);
71 co_spawn(executor,
72 [socket = std::move(socket)]() mutable
73 {
74 return echo(std::move(socket));
75 },
76 detached);
77 }
78 }
79
80 int main()
81 {
82 try
83 {
84 boost::asio::io_context io_context(1);
85
86 boost::asio::signal_set signals(io_context, SIGINT, SIGTERM);
87 signals.async_wait([&](auto, auto){ io_context.stop(); });
88
89 co_spawn(io_context, listener, detached);
90
91 io_context.run();
92 }
93 catch (std::exception& e)
94 {
95 std::printf("Exception: %s\n", e.what());
96 }
97 }