diff --git a/Makefile.am b/Makefile.am index 76331e6d..942e164d 100644 --- a/Makefile.am +++ b/Makefile.am @@ -26,6 +26,7 @@ EXTRA_PROGRAMS += subscriber EXTRA_PROGRAMS += commands if HAVE_CXX20 EXTRA_PROGRAMS += echo_server +EXTRA_PROGRAMS += echo_server_direct EXTRA_PROGRAMS += chat_room EXTRA_PROGRAMS += echo_server_client endif @@ -46,6 +47,7 @@ adapter_SOURCES = $(top_srcdir)/examples/adapter.cpp if HAVE_CXX20 test_high_level_SOURCES = $(top_srcdir)/tests/high_level.cpp echo_server_SOURCES = $(top_srcdir)/examples/echo_server.cpp +echo_server_direct_SOURCES = $(top_srcdir)/tools/echo_server_direct.cpp chat_room_SOURCES = $(top_srcdir)/examples/chat_room.cpp echo_server_client_SOURCES = $(top_srcdir)/tools/echo_server_client.cpp endif diff --git a/tools/echo_server_direct.cpp b/tools/echo_server_direct.cpp new file mode 100644 index 00000000..d1664afd --- /dev/null +++ b/tools/echo_server_direct.cpp @@ -0,0 +1,55 @@ +/* Copyright (c) 2018-2022 Marcelo Zimbres Silva (mzimbres@gmail.com) + * + * Distributed under the Boost Software License, Version 1.0. (See + * accompanying file LICENSE.txt) + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace net = boost::asio; +namespace this_coro = net::this_coro; +using net::ip::tcp; +using net::awaitable; +using net::co_spawn; +using net::detached; +using net::use_awaitable; + +awaitable echo(tcp::socket socket) +{ + try { + char data[1024]; + for (;;) { + std::size_t n = co_await socket.async_read_some(net::buffer(data), use_awaitable); + co_await async_write(socket, net::buffer(data, n), use_awaitable); + } + } catch (std::exception const& e) { + std::printf("echo Exception: %s\n", e.what()); + } +} + +awaitable listener() +{ + auto executor = co_await this_coro::executor; + tcp::acceptor acceptor(executor, {tcp::v4(), 55555}); + for (;;) { + tcp::socket socket = co_await acceptor.async_accept(use_awaitable); + co_spawn(executor, echo(std::move(socket)), detached); + } +} + +int main() +{ + try { + net::io_context io_context(1); + co_spawn(io_context, listener(), detached); + io_context.run(); + } catch (std::exception& e) { + std::printf("Exception: %s\n", e.what()); + } +}