diff options
| author | littleblack111 <littleblack11111@gmail.com> | 2025-06-18 09:07:50 +0800 |
|---|---|---|
| committer | littleblack111 <littleblack11111@gmail.com> | 2025-06-18 09:07:50 +0800 |
| commit | 0804c1285fe16977bce9f69c426a59994bebf594 (patch) | |
| tree | 26496e5d138c77d819d29a1d22b1bac46cea4bc1 | |
| parent | b46ba43e06aba714abc0afb29566a56d69891691 (diff) | |
feat: shutdownClients accepts an optional cb func now
fix: disallow creation of multiple clientManager
| -rw-r--r-- | include/libsock/server/client.hpp | 2 | ||||
| -rw-r--r-- | src/server/clients.cpp | 15 |
2 files changed, 8 insertions, 9 deletions
diff --git a/include/libsock/server/client.hpp b/include/libsock/server/client.hpp index 6a5aa88..3b0d38d 100644 --- a/include/libsock/server/client.hpp +++ b/include/libsock/server/client.hpp @@ -89,7 +89,7 @@ class Clients { void addClient(const Client &client); bool nameExists(const std::string &name); - void shutdownClients(); + void shutdownClients(std::optional<std::function<std::any(const std::vector<std::pair<std::jthread, SP<Client>>> &)>> cb = std::nullopt); SP<Client> getByName(const std::string &name) const; SP<Client> getByIp(const std::string &ip) const; diff --git a/src/server/clients.cpp b/src/server/clients.cpp index 210581a..d3a9908 100644 --- a/src/server/clients.cpp +++ b/src/server/clients.cpp @@ -3,22 +3,18 @@ #include <any> #include <format> #include <ranges> +#include <stdexcept> #include <unistd.h> #include <utility> using namespace LibSock::Server; -void Clients::shutdownClients() { +void Clients::shutdownClients(std::optional<std::function<std::any(const std::vector<std::pair<std::jthread, SP<Client>>> &)>> cb) { if (m_vClients.empty()) return; - for (auto &[thread, client] : m_vClients) { - if (client) { - client->write("Server shutting down"); - if (!client->getName().empty()) - broadcast(std::format("{} has left the chat", client->getName()), WP<Client>(client)); - } - } + if (cb) + (*cb)(m_vClients); for (auto &[thread, client] : m_vClients) { if (thread.joinable()) @@ -34,6 +30,9 @@ Clients::Clients() { // shutdownClients(); // })) // void(); // failed to register exit handler... + if (pClients) + throw std::runtime_error("server:client: ClientManager already exist"); + pClients = SP<Clients>(this); }; |
