Boost.Redis: example/cpp20_echo_server.cpp Source File

Boost.Redis 1.84.0 A redis client library

Loading...
Searching...
No Matches
cpp20_echo_server.cpp
1/* Copyright (c) 2018-2022 Marcelo Zimbres Silva (mzimbres@gmail.com)
2 *
3 * Distributed under the Boost Software License, Version 1.0. (See
4 * accompanying file LICENSE.txt)
5 */
6
7#include <boost/redis/connection.hpp>
8#include <boost/asio/deferred.hpp>
9#include <boost/asio/signal_set.hpp>
10#include <boost/asio/detached.hpp>
11#include <boost/asio/redirect_error.hpp>
12#include <boost/asio/co_spawn.hpp>
13#include <iostream>
14
15#if defined(BOOST_ASIO_HAS_CO_AWAIT)
16
17namespace asio = boost::asio;
18using tcp_socket = asio::deferred_t::as_default_on_t<asio::ip::tcp::socket>;
19using tcp_acceptor = asio::deferred_t::as_default_on_t<asio::ip::tcp::acceptor>;
20using signal_set = asio::deferred_t::as_default_on_t<asio::signal_set>;
21using boost::redis::request;
22using boost::redis::response;
23using boost::redis::config;
24using boost::system::error_code;
25using boost::redis::connection;
26using namespace std::chrono_literals;
27
28auto echo_server_session(tcp_socket socket, std::shared_ptr<connection> conn) -> asio::awaitable<void>
29{
30 request req;
31 response<std::string> resp;
32
33 for (std::string buffer;;) {
34 auto n = co_await asio::async_read_until(socket, asio::dynamic_buffer(buffer, 1024), "\n");
35 req.push("PING", buffer);
36 co_await conn->async_exec(req, resp, asio::deferred);
37 co_await asio::async_write(socket, asio::buffer(std::get<0>(resp).value()));
38 std::get<0>(resp).value().clear();
39 req.clear();
40 buffer.erase(0, n);
41 }
42}
43
44// Listens for tcp connections.
45auto listener(std::shared_ptr<connection> conn) -> asio::awaitable<void>
46{
47 try {
48 auto ex = co_await asio::this_coro::executor;
49 tcp_acceptor acc(ex, {asio::ip::tcp::v4(), 55555});
50 for (;;)
51 asio::co_spawn(ex, echo_server_session(co_await acc.async_accept(), conn), asio::detached);
52 } catch (std::exception const& e) {
53 std::clog << "Listener: " << e.what() << std::endl;
54 }
55}
56
57// Called from the main function (see main.cpp)
58auto co_main(config cfg) -> asio::awaitable<void>
59{
60 auto ex = co_await asio::this_coro::executor;
61 auto conn = std::make_shared<connection>(ex);
62 asio::co_spawn(ex, listener(conn), asio::detached);
63 conn->async_run(cfg, {}, asio::consign(asio::detached, conn));
64
65 signal_set sig_set(ex, SIGINT, SIGTERM);
66 co_await sig_set.async_wait();
67 conn->cancel();
68}
69
70#endif // defined(BOOST_ASIO_HAS_CO_AWAIT)
boost::redis::connection
A basic_connection that type erases the executor.
Definition: connection.hpp:339
boost::redis::request
Creates Redis requests.
Definition: request.hpp:46
boost::redis::response
std::tuple< adapter::result< Ts >... > response
Response with compile-time size.
Definition: response.hpp:25
boost::redis::config
Configure parameters used by the connection classes.
Definition: config.hpp:30