12 #include <boost/asio.hpp>
14 namespace net = boost::asio;
15 namespace this_coro = net::this_coro;
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;
26 awaitable_type echo(tcp_socket socket)
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);
34 }
catch (std::exception
const& e) {
39 awaitable_type listener()
41 auto ex = co_await this_coro::executor;
42 tcp_acceptor acceptor(ex, {tcp::v4(), 55555});
44 tcp_socket socket = co_await acceptor.async_accept(use_awaitable);
45 co_spawn(ex, echo(std::move(socket)), detached);
52 net::io_context io_context{BOOST_ASIO_CONCURRENCY_HINT_UNSAFE_IO};
53 co_spawn(io_context, listener(), detached);
55 }
catch (std::exception
const& e) {
56 std::printf(
"Exception: %s\n", e.what());