summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--include/libsock/server/clients.hpp3
-rw-r--r--src/server/clients.cpp13
2 files changed, 12 insertions, 4 deletions
diff --git a/include/libsock/server/clients.hpp b/include/libsock/server/clients.hpp
index 4b67c23..2591cc3 100644
--- a/include/libsock/server/clients.hpp
+++ b/include/libsock/server/clients.hpp
@@ -7,6 +7,7 @@
#include <optional>
#include <string>
#include <thread>
+#include <future>
#include <vector>
namespace LibSock {
@@ -24,7 +25,7 @@ class Clients : public std::enable_shared_from_this<Clients> {
static SP<Clients> create(WP<Server> server);
~Clients();
- SP<Client> newClient(std::function<void(SP<Client> &)> cb = [](SP<Client>) {}, bool track = true, bool wait = false);
+ std::future<SP<Client>> newClient(std::function<void(SP<Client> &)> cb = [](SP<Client>) {}, bool track = true, bool wait = false);
void broadcast(const std::string &msg, std::optional<WP<Client>> self = std::nullopt); // second param only specified when we
// want to exclude the sender
diff --git a/src/server/clients.cpp b/src/server/clients.cpp
index 5337769..8bb85a3 100644
--- a/src/server/clients.cpp
+++ b/src/server/clients.cpp
@@ -2,6 +2,7 @@
#include "libsock/server/client.hpp"
#include <algorithm>
#include <functional>
+#include <future>
#include <ranges>
#include <unistd.h>
#include <utility>
@@ -59,11 +60,17 @@ Clients::~Clients() {
vpClients.erase(std::remove_if(vpClients.begin(), vpClients.end(), [this](const WP<Clients> &wptr) { return !wptr.owner_before(m_self) && !m_self.owner_before(wptr); }), vpClients.end());
}
-SP<Client> Clients::newClient(std::function<void(SP<Client> &)> cb, bool track, bool wait) {
+std::future<SP<Client>> Clients::newClient(std::function<void(SP<Client> &)> cb, bool track, bool wait) {
+ auto promise = std::make_shared<std::promise<SP<Client>>>();
SP client = SP<Client>(new Client(m_wpServer.lock(), shared_from_this(), track, wait));
- auto &instance = m_vClients.emplace_back(std::jthread([&client, &cb]() { client->init(); cb(client); }), client);
+ auto &instance = m_vClients.emplace_back(std::jthread([client, cb, promise]() mutable {
+ client->init();
+ promise->set_value(client);
+ cb(client);
+ }),
+ client);
instance.second->m_self = std::weak_ptr<Client>(instance.second);
- return client;
+ return promise->get_future();
}
void Clients::broadcast(const std::string &msg, std::optional<std::weak_ptr<Client>> self) {