From 7ea298254dcf5268f8e304a434a466d9f8054e16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Stoj=C5=A1in?= Date: Tue, 25 Jun 2024 15:15:02 +0200 Subject: [PATCH] Update client disconnect callback - add flag to differentiate between user requested disconnects and network disconnects --- include/libnetwrk/net/core/client/client.hpp | 34 +++++++++++-------- .../net/core/client/client_context.hpp | 2 +- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/include/libnetwrk/net/core/client/client.hpp b/include/libnetwrk/net/core/client/client.hpp index 83422eb..ec0375f 100644 --- a/include/libnetwrk/net/core/client/client.hpp +++ b/include/libnetwrk/net/core/client/client.hpp @@ -37,7 +37,7 @@ namespace libnetwrk { m_context.cb_internal_disconnect = [this](auto) { std::thread t = std::thread([this] { - this->disconnect(); + this->internal_disconnect(false); }); t.detach(); }; @@ -79,18 +79,7 @@ namespace libnetwrk { Disconnect the client and clean up. */ void disconnect() { - if (m_context.status != to_underlying(service_status::started)) - return; - - m_context.status = to_underlying(service_status::stopping); - this->teardown(); - - if (m_context.cb_disconnect) - m_context.cb_disconnect(); - - LIBNETWRK_INFO(m_context.name, "Disconnected."); - - m_context.status = to_underlying(service_status::stopped); + internal_disconnect(true); } void send(message_t& message, libnetwrk::send_flags flags = libnetwrk::send_flags::none) { @@ -148,7 +137,8 @@ namespace libnetwrk { /* Set disconnected callback - @param void() func + @param void(bool) func + @param bool -> user initiated disconnect */ void set_disconnect_callback(context_t::cb_disconnect_t cb) { if (!m_context.cb_disconnect) @@ -197,5 +187,21 @@ namespace libnetwrk { virtual bool connect_impl(const std::string& host, const uint16_t port) { return false; } + + private: + virtual void internal_disconnect(bool user_initiated) { + if (m_context.status != to_underlying(service_status::started)) + return; + + m_context.status = to_underlying(service_status::stopping); + this->teardown(); + + if (m_context.cb_disconnect) + m_context.cb_disconnect(user_initiated); + + LIBNETWRK_INFO(m_context.name, "Disconnected."); + + m_context.status = to_underlying(service_status::stopped); + } }; } diff --git a/include/libnetwrk/net/core/client/client_context.hpp b/include/libnetwrk/net/core/client/client_context.hpp index cdb4575..2524bc7 100644 --- a/include/libnetwrk/net/core/client/client_context.hpp +++ b/include/libnetwrk/net/core/client/client_context.hpp @@ -12,7 +12,7 @@ namespace libnetwrk { template class client_context : public shared_context { public: - using cb_disconnect_t = std::function; + using cb_disconnect_t = std::function; public: client_settings settings;