virthttp  0.0
libvirt http interface
tcp_listener.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <boost/beast.hpp>
4 #include "../general_store.hpp"
5 #include "http1/Session.hpp"
6 //#include "http2/Session.hpp"
7 
8 // Accepts incoming connections and launches the sessions
9 class TcpListener : public std::enable_shared_from_this<TcpListener> {
10  boost::beast::net::ip::tcp::acceptor acceptor_;
11  boost::beast::net::ip::tcp::socket socket_;
12  std::reference_wrapper<GeneralStore> gstore;
13 
14  public:
15  TcpListener(boost::beast::net::io_context& ioc, const boost::beast::net::ip::tcp::endpoint& endpoint, GeneralStore& gstore)
16  : acceptor_(ioc), socket_(ioc), gstore(gstore) {
17  boost::beast::error_code ec;
18 
19  // Open the acceptor
20  acceptor_.open(endpoint.protocol(), ec);
21  if (ec) {
22  fail(ec, "open");
23  return;
24  }
25 
26  // Allow address reuse
27  acceptor_.set_option(boost::beast::net::socket_base::reuse_address(true), ec);
28  if (ec) {
29  fail(ec, "set_option");
30  return;
31  }
32 
33  // Bind to the server address
34  acceptor_.bind(endpoint, ec);
35  if (ec) {
36  fail(ec, "bind");
37  return;
38  }
39 
40  // Start listening for connections
41  acceptor_.listen(boost::beast::net::socket_base::max_listen_connections, ec);
42  if (ec) {
43  fail(ec, "listen");
44  return;
45  }
46  }
47 
48  // Start accepting incoming connections
49  void run() {
50  if (!acceptor_.is_open())
51  return;
52  do_accept();
53  }
54 
55  void do_accept() { acceptor_.async_accept(socket_, std::bind(&TcpListener::on_accept, shared_from_this(), std::placeholders::_1)); }
56 
57  void on_accept(boost::beast::error_code ec) {
58  if (ec)
59  fail(ec, "accept");
60  else {
61  // Create the Session and run it
63  std::make_shared<Session>(std::move(socket_), gstore)->run();
64  }
65 
66  // Accept another connection
67  do_accept();
68  }
69 };
void run()
Definition: tcp_listener.hpp:49
Definition: tcp_listener.hpp:9
TcpListener(boost::beast::net::io_context &ioc, const boost::beast::net::ip::tcp::endpoint &endpoint, GeneralStore &gstore)
Definition: tcp_listener.hpp:15
void do_accept()
Definition: tcp_listener.hpp:55
void fail(boost::beast::error_code ec, const char *what)
Definition: beast_internals.hpp:6
void on_accept(boost::beast::error_code ec)
Definition: tcp_listener.hpp:57
Definition: general_store.hpp:5