-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathconnection.cpp
108 lines (86 loc) · 2.06 KB
/
connection.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
105
106
107
108
#include <stdexcept>
#include <thread>
#include <functional>
#include <boost/bind.hpp>
#include "logger.h"
#include "connection.h"
namespace clever_bot {
void connection::connect()
{
boost::asio::ip::tcp::resolver resolver(m_io_service);
boost::asio::ip::tcp::resolver::query query(m_addr, m_port);
boost::system::error_code error = boost::asio::error::host_not_found;
auto iter = resolver.resolve(query);
decltype(iter) end;
while (iter != end) {
if (!error) {
break;
}
m_socket.close();
LOG("Info", "Trying to connect: " + m_addr + ":" + m_port);
m_socket.connect(*iter++, error);
if (error) {
LOG("ERROR", error.message());
}
}
if (error) {
throw std::runtime_error(error.message());
}
LOG("Info", "Connected!");
}
void connection::run()
{
std::thread write_handler_thread(m_write_handler);
m_socket.async_read_some(boost::asio::buffer(m_buffer),
boost::bind(&connection::read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
m_io_service.run();
write_handler_thread.join();
}
bool connection::alive() const
{
return m_socket.is_open();
}
void connection::close()
{
m_socket.close();
m_io_service.stop();
}
void connection::connect(const std::string& addr, const std::string& port)
{
m_addr = addr;
m_port = port;
connect();
}
void connection::write(const std::string& content)
{
LOG("Write", content);
boost::asio::write(m_socket, boost::asio::buffer(content + "\r\n"));
}
void connection::read(const boost::system::error_code& error, std::size_t count)
{
if (error) {
close();
}
else {
m_read_handler(std::string(m_buffer.data(), count));
m_socket.async_read_some(boost::asio::buffer(m_buffer),
boost::bind(&connection::read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
}
}
void connection::set_read_handler(const read_handler_type& handler)
{
m_read_handler = handler;
}
void connection::set_write_handler(const write_handler_type& handler)
{
m_write_handler = handler;
}
} // ns clever_bot