-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.cpp
102 lines (92 loc) · 2.1 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
#include "Connection.h"
#include <vector>
#include <boost/bind.hpp>
#include "RequestHandler.h"
namespace http {
namespace server {
Connection::Connection(
boost::asio::io_service& ioService,
RequestHandler& handler
) :
strand_(ioService),
socket_(ioService),
requestHandler_(handler) {}
boost::asio::ip::tcp::socket& Connection::getSocket() {return socket_;}
void Connection::start()
{
socket_.async_read_some(
boost::asio::buffer(buffer_),
strand_.wrap(
boost::bind(
&Connection::handleRead,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
)
);
}
void Connection::handleRead(
const boost::system::error_code& e,
std::size_t bytes_transferred
)
{
if (!e) {
bool result = requestParser_.isValidRequest(
request_,
buffer_.data(),
buffer_.data() + bytes_transferred
);
if (result) {
requestHandler_.handleRequest(request_, response_);
boost::asio::async_write(
socket_,
response_.toBuffers(),
strand_.wrap(
boost::bind(
&Connection::handleWrite,
shared_from_this(),
boost::asio::placeholders::error
)
)
);
} else if (!result) {
response_ = HttpResponse::defaultResponse(HttpResponse::bad_request);
boost::asio::async_write(
socket_,
response_.toBuffers(),
strand_.wrap(
boost::bind(
&Connection::handleWrite,
shared_from_this(),
boost::asio::placeholders::error
)
)
);
} else {
socket_.async_read_some(
boost::asio::buffer(buffer_),
strand_.wrap(
boost::bind(
&Connection::handleRead,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
)
);
}
}
}
void Connection::handleWrite(const boost::system::error_code& e)
{
if (!e) {
boost::system::error_code ignored_ec;
socket_.shutdown(
boost::asio::ip::tcp::socket::shutdown_both,
ignored_ec
);
}
}
}
}