-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cpp
104 lines (86 loc) · 2.88 KB
/
Server.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
96
97
98
99
100
101
102
103
104
//
// Copyright 2018 - 2025 (C). Alex Robenko. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "Server.h"
#include <iostream>
namespace cc_demo3
{
namespace server
{
Server::Server(common::boost_wrap::io& io, std::uint16_t port)
: m_io(io),
m_acceptor(io),
m_socket(io),
m_port(port)
{
}
bool Server::start()
{
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), m_port);
boost::system::error_code ec;
m_acceptor.open(endpoint.protocol(), ec);
if (ec) {
std::cerr << "Failed to open acceptor on port " << m_port << " with error: " << ec.message() << std::endl;
return false;
}
m_acceptor.bind(
boost::asio::ip::tcp::endpoint(
boost::asio::ip::tcp::v4(),
m_port
),
ec);
if (ec) {
std::cerr << "Failed to bind port " << m_port << " with error: " << ec.message() << std::endl;
return false;
}
m_acceptor.listen(Socket::max_listen_connections, ec);
if (ec) {
std::cerr << "Failed to listen on port " << m_port << " with error: " << ec.message() << std::endl;
return false;
}
acceptNewConnection();
return true;
}
void Server::acceptNewConnection()
{
m_acceptor.async_accept(
m_socket,
[this](const boost::system::error_code& ec2)
{
if (ec2) {
std::cerr << "WARNING: failed to accept new connection with error: " <<
ec2.message() << std::endl;
acceptNewConnection();
return;
}
std::cerr << "New connection from " << m_socket.remote_endpoint() << std::endl;
SessionPtr newSession(new Session(m_io, std::move(m_socket)));
auto* sessionPtr = newSession.get();
newSession->setTerminateCallback(
[this, sessionPtr]()
{
auto iter =
std::find_if(
m_sessions.begin(), m_sessions.end(),
[sessionPtr](auto& s)
{
return s.get() == sessionPtr;
});
if (iter == m_sessions.end()) {
static constexpr bool Unexpected_error = false;
static_cast<void>(Unexpected_error);
assert(Unexpected_error);
return;
}
m_sessions.erase(iter);
});
newSession->start();
m_sessions.push_back(std::move(newSession));
acceptNewConnection();
});
}
} // namespace server
} // namespace cc_demo3