Aedis 0.2.1  
High level Redis client
echo_server_direct.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 <cstdio>
12 #include <boost/asio.hpp>
13 
14 namespace net = boost::asio;
15 namespace this_coro = net::this_coro;
16 using net::ip::tcp;
17 using net::detached;
18 using executor_type = net::io_context::executor_type;
19 using socket_type = net::basic_stream_socket<net::ip::tcp, executor_type>;
20 using tcp_socket = net::use_awaitable_t<executor_type>::as_default_on_t<socket_type>;
21 using acceptor_type = net::basic_socket_acceptor<net::ip::tcp, executor_type>;
22 using tcp_acceptor = net::use_awaitable_t<executor_type>::as_default_on_t<acceptor_type>;
23 using awaitable_type = net::awaitable<void, executor_type>;
24 constexpr net::use_awaitable_t<executor_type> use_awaitable;
25 
26 awaitable_type echo(tcp_socket socket)
27 {
28  try {
29  char data[1024];
30  for (;;) {
31  std::size_t n = co_await socket.async_read_some(net::buffer(data), use_awaitable);
32  co_await async_write(socket, net::buffer(data, n), use_awaitable);
33  }
34  } catch (std::exception const& e) {
35  //std::printf("echo Exception: %s\n", e.what());
36  }
37 }
38 
39 awaitable_type listener()
40 {
41  auto ex = co_await this_coro::executor;
42  tcp_acceptor acceptor(ex, {tcp::v4(), 55555});
43  for (;;) {
44  tcp_socket socket = co_await acceptor.async_accept(use_awaitable);
45  co_spawn(ex, echo(std::move(socket)), detached);
46  }
47 }
48 
49 int main()
50 {
51  try {
52  net::io_context io_context{BOOST_ASIO_CONCURRENCY_HINT_UNSAFE_IO};
53  co_spawn(io_context, listener(), detached);
54  io_context.run();
55  } catch (std::exception const& e) {
56  std::printf("Exception: %s\n", e.what());
57  }
58 }