| 1 | #include "abstractthreadedserver.h" |
|---|---|
| 2 | |
| 3 | using namespace jsonrpc; |
| 4 | using namespace std; |
| 5 | |
| 6 | AbstractThreadedServer::AbstractThreadedServer(size_t threads) : running(false), threadPool(threads), threads(threads) {} |
| 7 | |
| 8 | AbstractThreadedServer::~AbstractThreadedServer() { this->StopListening(); } |
| 9 | |
| 10 | bool 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 | |
| 24 | bool AbstractThreadedServer::StopListening() { |
| 25 | if (!this->running) |
| 26 | return false; |
| 27 | |
| 28 | this->running = false; |
| 29 | |
| 30 | this->listenerThread->join(); |
| 31 | return true; |
| 32 | } |
| 33 | |
| 34 | void 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 |