From 9b61c218b665f94f5cc383a5e607b951ce6af121 Mon Sep 17 00:00:00 2001 From: littleblack111 Date: Sun, 22 Jun 2025 15:09:42 +0800 Subject: refactor(server): properly use weak pointer API!(server/client:create): require manually specifying server API!(server/client:newClient): now returns a SP instead of WP --- src/server/clients.cpp | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) (limited to 'src/server/clients.cpp') diff --git a/src/server/clients.cpp b/src/server/clients.cpp index e1dd161..a274224 100644 --- a/src/server/clients.cpp +++ b/src/server/clients.cpp @@ -2,7 +2,6 @@ #include "libsock/server/client.hpp" #include #include -#include #include #include @@ -29,24 +28,25 @@ void Clients::shutdownClients(std::optionalshutdownClients(); + for (auto c : vpClients) + if (const auto p = c.lock()) + p->shutdownClients(); })) void(); // failed to register exit handler... } -SP Clients::create() { - if (pClients) - throw std::runtime_error("server:clients ClientManager already exist"); - - pClients = SP(new Clients()); - return pClients; +SP Clients::create(WP server) { + auto c = SP(new Clients()); + vpClients.emplace_back(c); + c->m_self = c; + c->m_wpServer = server; + return c; } -SP Clients::get() { - if (!pClients) - pClients = shared_from_this(); - return pClients; +WP Clients::get() { + if (m_self.expired()) + m_self = shared_from_this(); + return m_self; } Clients::~Clients() { @@ -55,13 +55,14 @@ Clients::~Clients() { thread.detach(); kick(WP(client)); } + vpClients.erase(std::remove_if(vpClients.begin(), vpClients.end(), [this](const WP &wptr) { return !wptr.owner_before(m_self) && !m_self.owner_before(wptr); }), vpClients.end()); } -WP Clients::newClient(std::function &)> loopFunc, SP server) { - SP client = SP(new Client(server, shared_from_this())); - auto &instance = m_vClients.emplace_back(std::jthread([&client, &loopFunc]() { loopFunc(client); }), client); - instance.second->self = std::weak_ptr(instance.second); - return instance.second; +SP Clients::newClient(std::function &)> loopFunc) { + SP client = SP(new Client(m_wpServer.lock(), shared_from_this())); + auto &instance = m_vClients.emplace_back(std::jthread([&client, &loopFunc]() { loopFunc(client); }), client); + instance.second->m_self = std::weak_ptr(instance.second); + return client; } void Clients::broadcast(const std::string &msg, std::optional> self) { -- cgit v1.2.3