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/signal_set.hpp>
9#include <boost/asio/detached.hpp>
10#include <boost/asio/redirect_error.hpp>
11#include <boost/asio/co_spawn.hpp>
12#include <iostream>
13
14#if defined(BOOST_ASIO_HAS_CO_AWAIT)
15
16namespace asio = boost::asio;
17using boost::asio::signal_set;
18using boost::redis::request;
19using boost::redis::response;
20using boost::redis::config;
21using boost::system::error_code;
22using boost::redis::connection;
23using namespace std::chrono_literals;
24
25auto
26echo_server_session(
27 asio::ip::tcp::socket socket,
28 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);
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 asio::ip::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:1231
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