-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.cpp
83 lines (71 loc) · 1.71 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
#include "Server.h"
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
namespace http {
namespace server {
Server::Server(
const std::string& address,
const std::string& port,
std::size_t threadPoolSize
) :
threadPoolSize_(threadPoolSize),
acceptor_(ioService_),
newConnection_(new Connection(ioService_, requestHandler_)),
requestHandler_()
{
boost::asio::ip::tcp::resolver resolver(ioService_);
boost::asio::ip::tcp::resolver::query query(address, port);
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
acceptor_.open(endpoint.protocol());
acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor_.bind(endpoint);
acceptor_.listen();
acceptor_.async_accept(
newConnection_->getSocket(),
boost::bind(
&Server::handleAccept,
this,
boost::asio::placeholders::error
)
);
}
void Server::run()
{
std::vector<boost::shared_ptr<boost::thread> > threads;
for (std::size_t i = 0; i < threadPoolSize_; ++i) {
boost::shared_ptr<boost::thread> thread(
new boost::thread(
boost::bind(
&boost::asio::io_service::run,
&ioService_
)
)
);
threads.push_back(thread);
}
for (std::size_t i = 0; i < threads.size(); ++i)
threads[i]->join();
}
void Server::stop()
{
ioService_.stop();
}
void Server::handleAccept(const boost::system::error_code& e)
{
if (!e) {
newConnection_->start();
newConnection_.reset(new Connection(ioService_, requestHandler_));
acceptor_.async_accept(
newConnection_->getSocket(),
boost::bind(
&Server::handleAccept,
this,
boost::asio::placeholders::error
)
);
}
}
}
}