Skip to content

Commit

Permalink
Refactor server class to add running flag and stop() method
Browse files Browse the repository at this point in the history
  • Loading branch information
riccardodebenedictis committed Apr 19, 2024
1 parent 590c585 commit 16e5a97
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
1 change: 1 addition & 0 deletions include/server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ namespace network
void handle_request(std::unique_ptr<request> req);

private:
bool running = false; // The server is running
boost::asio::io_context io_ctx; // The io_context is required for all I/O
std::vector<std::thread> threads; // The thread pool
boost::asio::ip::tcp::endpoint endpoint; // The endpoint for the server
Expand Down
8 changes: 7 additions & 1 deletion src/server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
namespace network
{
server::server(const std::string &address, unsigned short port, std::size_t concurrency_hint) : io_ctx(concurrency_hint), endpoint(boost::asio::ip::make_address(address), port), acceptor(boost::asio::make_strand(io_ctx)) { threads.reserve(concurrency_hint); }
server::~server() { stop(); }
server::~server()
{
if (running)
stop();
}

void server::start()
{
Expand Down Expand Up @@ -36,6 +40,7 @@ namespace network
return;
}

running = true;
do_accept();

for (auto i = threads.capacity(); i > 0; --i)
Expand All @@ -51,6 +56,7 @@ namespace network
io_ctx.stop();
for (auto &thread : threads)
thread.join();
running = false;
}

void server::do_accept() { acceptor.async_accept(io_ctx, std::bind(&server::on_accept, this, std::placeholders::_1, std::placeholders::_2)); }
Expand Down
5 changes: 4 additions & 1 deletion tests/test_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
int main(int argc, char const *argv[])
{
network::server server;
server.start();

std::thread t{[&server]
{ server.start(); }};
std::this_thread::sleep_for(std::chrono::seconds(10));
server.stop();
t.join();

return 0;
}

0 comments on commit 16e5a97

Please sign in to comment.