-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistener.cpp
95 lines (85 loc) · 2.06 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
85
86
87
88
89
90
91
92
93
94
95
//
// Copyright (c) 2018 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/vinniefalco/CppCon2018
//
#include "listener.hpp"
#include "websocket_session.hpp"
#include <iostream>
listener::listener(
asio::io_context& ioc,
tcp::endpoint endpoint,
std::shared_ptr<shared_state> const& state)
: acceptor_(ioc)
, socket_(ioc)
, state_(state)
{
error_code ec;
// Open the acceptor
acceptor_.open(endpoint.protocol(), ec);
if(ec)
{
fail(ec, "open");
return;
}
// Allow address reuse
acceptor_.set_option(asio::socket_base::reuse_address(true));
if(ec)
{
fail(ec, "set_option");
return;
}
// Bind to the server address
acceptor_.bind(endpoint, ec);
if(ec)
{
fail(ec, "bind");
return;
}
// Start listening for connections
acceptor_.listen(asio::socket_base::max_listen_connections, ec);
if(ec)
{
fail(ec, "listen");
return;
}
}
void listener::run()
{
// Start accepting a connection
acceptor_.async_accept(
socket_,
[self = shared_from_this()](error_code ec)
{
self->on_accept(ec);
});
}
// Report a failure
void listener::fail(error_code ec, char const* what)
{
// Don't report on canceled operations
if(ec == asio::error::operation_aborted)
return;
std::cerr << what << ": " << ec.message() << "\n";
}
// Handle a connection
void listener::on_accept(error_code ec)
{
if(ec)
return fail(ec, "accept");
else
// Launch a new session for this connection
std::make_shared<websocket_session>(
std::move(socket_),
state_)->run();
// Accept another connection
acceptor_.async_accept(
socket_,
[self = shared_from_this()](error_code ec)
{
self->on_accept(ec);
});
}