Skip to content

Commit

Permalink
Update client disconnect callback
Browse files Browse the repository at this point in the history
- add flag to differentiate between user requested disconnects and network disconnects
  • Loading branch information
dvsku committed Jun 25, 2024
1 parent d8ce016 commit 7ea2982
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
34 changes: 20 additions & 14 deletions include/libnetwrk/net/core/client/client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
};
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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);
}
};
}
2 changes: 1 addition & 1 deletion include/libnetwrk/net/core/client/client_context.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace libnetwrk {
template<typename Connection>
class client_context : public shared_context<Connection> {
public:
using cb_disconnect_t = std::function<void()>;
using cb_disconnect_t = std::function<void(bool)>;

public:
client_settings settings;
Expand Down

0 comments on commit 7ea2982

Please sign in to comment.