1#include "abstractthreadedserver.h"
2
3using namespace jsonrpc;
4using namespace std;
5
6AbstractThreadedServer::AbstractThreadedServer(size_t threads) : running(false), threadPool(threads), threads(threads) {}
7
8AbstractThreadedServer::~AbstractThreadedServer() { this->StopListening(); }
9
10bool AbstractThreadedServer::StartListening() {
11 if (this->running)
12 return false;
13
14 if (!this->InitializeListener())
15 return false;
16
17 this->running = true;
18
19 this->listenerThread = unique_ptr<thread>(new thread(&AbstractThreadedServer::ListenLoop, this));
20
21 return true;
22}
23
24bool AbstractThreadedServer::StopListening() {
25 if (!this->running)
26 return false;
27
28 this->running = false;
29
30 this->listenerThread->join();
31 return true;
32}
33
34void AbstractThreadedServer::ListenLoop() {
35 while (this->running) {
36 int conn = this->CheckForConnection();
37
38 if (conn > 0) {
39 if (this->threads > 0) {
40 this->threadPool.enqueue(&AbstractThreadedServer::HandleConnection, this, conn);
41 } else {
42 this->HandleConnection(conn);
43 }
44 } else {
45 std::this_thread::sleep_for(std::chrono::milliseconds(1));
46 }
47 }
48}
49