-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.cpp
44 lines (37 loc) · 1.47 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
//
// Created by lupusanay on 27.12.17.
//
#include "Server.h"
Server::Server(unsigned short port, unsigned short thread_count) :
acceptor(service, ip::tcp::endpoint(ip::tcp::v4(), port)),
threads(thread_count) {
// Can use the address already used
acceptor.listen();
startAccept();
// Fills the thread pool with pointers to threads that execute io_service::run
generate(threads.begin(), threads.end(),
boost::bind(
&boost::make_shared<boost::thread, boost::function<void()> const &>,
boost::function<void()>(boost::bind(&io_service::run, &service))));
}
Server::~Server() {
for_each(threads.begin(), threads.end(),
boost::bind(&io_service::stop, &service));
for_each(threads.begin(), threads.end(),
boost::bind(&boost::thread::join, _1));
}
void Server::handleAccept(const boost::system::error_code &error) {
if (!error) {
newConnection->start();
} else {
cout << "Error while accepting: " << error.message() << endl;
}
startAccept();
}
// Creates a Connection object in the newConnection variable
// and then asynchronously waits for the connection to be received. Uses a handleAccept as a callback
void Server::startAccept() {
newConnection = boost::make_shared<Connection, io_service &>(service);
acceptor.async_accept(newConnection->getSocket(),
boost::bind(&Server::handleAccept, this, _1));
}