-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlistener.cpp
84 lines (74 loc) · 1.68 KB
/
listener.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "listener.h"
#include <iostream>
#include <memory>
#include "session/tcp_session.h"
#include "session/http_session.h"
// Report a failure
void
fail(boost::system::error_code ec, char const* what)
{
std::cerr << what << ": " << ec.message() << "\n";
}
listener::listener(
boost::asio::io_context& ioc,
tcp::endpoint endpoint,
std::string& protocol,
std::shared_ptr<peer_channal_delegate> pcd)
: acceptor_(ioc)
, socket_(ioc)
, protocol_(protocol)
, pcd_(pcd)
{
boost::system::error_code ec;
// Open the acceptor
acceptor_.open(endpoint.protocol(), ec);
if(ec)
{
fail(ec, "open");
return;
}
// Bind to the server address
acceptor_.bind(endpoint, ec);
if(ec)
{
fail(ec, "bind");
return;
}
// Start listening for connections
acceptor_.listen(
boost::asio::socket_base::max_listen_connections, ec);
if(ec)
{
fail(ec, "listen");
return;
}
}
// Start accepting incoming connections
void listener::run() {
if(! acceptor_.is_open())
return;
do_accept();
}
void listener::do_accept() {
acceptor_.async_accept(
socket_,
std::bind(
&listener::on_accept,
shared_from_this(),
std::placeholders::_1));
}
void listener::on_accept(boost::system::error_code ec) {
if(ec)
{
fail(ec, "accept");
}
else
{
if (protocol_ == "tcp")
std::make_shared<tcp_session>(std::move(socket_), pcd_)->run();
if (protocol_ == "http")
std::make_shared<http_session>(std::move(socket_), pcd_)->run();
}
// Accept another connection
do_accept();
}