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
|
#include "control_connection.hpp"
namespace wanda
{
control_connection::pointer make_control_connection(control_connection::protocol::socket &&socket)
{
return std::make_shared<control_connection>(control_connection::key{}, std::move(socket));
}
control_connection::control_connection(control_connection::key key, control_connection::protocol::socket socket)
: keyed{key},
m_socket{std::move(socket)}
{
}
bool control_connection::add(std::shared_ptr<control_connection::listener> listener)
{
auto [_, inserted] = m_listeners.insert(listener);
return inserted;
}
bool control_connection::remove(std::shared_ptr<control_connection::listener> listener)
{
return m_listeners.erase(listener);
}
void control_connection::start()
{
if (!m_running)
{
m_running = true;
perform_read();
}
}
void control_connection::close()
{
if (auto error = boost::system::error_code{}; m_socket.cancel(error))
{
for (auto &listener : m_listeners)
{
listener->on_error(shared_from_this(), error);
}
}
if (auto error = boost::system::error_code{}; m_socket.close(error))
{
for (auto &listener : m_listeners)
{
listener->on_error(shared_from_this(), error);
}
}
for (auto &listener : m_listeners)
{
listener->on_close(shared_from_this());
}
m_listeners.clear();
}
void control_connection::perform_read()
{
boost::asio::async_read_until(m_socket, m_in, '\n', [that = shared_from_this(), this](auto const &error, auto const length) {
if (error)
{
for (auto &listener : m_listeners)
{
listener->on_error(shared_from_this(), error);
}
close();
}
else
{
std::string message{};
std::getline(m_input, message);
for (auto &listener : m_listeners)
{
listener->on_received(shared_from_this(), message);
}
perform_read();
}
});
}
} // namespace wanda
|