diff --git a/Discord.C++/Gateway.cpp b/Discord.C++/Gateway.cpp index f512049..be8f664 100644 --- a/Discord.C++/Gateway.cpp +++ b/Discord.C++/Gateway.cpp @@ -44,8 +44,7 @@ void DiscordCPP::Gateway::start_heartbeating() { this->send(payload).get(); _log.debug("Heartbeat message has been sent"); } catch (const std::exception& e) { - _log.error("Cannot send heartbeat message: " + - std::string(e.what())); + _log.error("Cannot send heartbeat message: " + std::string(e.what())); } } } @@ -58,8 +57,11 @@ void DiscordCPP::Gateway::start_heartbeating() { void DiscordCPP::Gateway::on_websocket_disconnnect() { _connected = false; if (_keepalive == false) { + _reconnecting = false; + _reconnect_finished.notify_all(); return; } + _reconnecting = true; _log.info("Websocket connection closed"); threadpool->execute([this] { @@ -79,7 +81,11 @@ void DiscordCPP::Gateway::on_websocket_disconnnect() { _log.info("reconnected"); _reconnect_timeout = 0; _last_heartbeat_ack = time(nullptr); + _reconnecting = false; + _reconnect_finished.notify_all(); } catch (const beast::system_error& e) { + _reconnecting = false; + _reconnect_finished.notify_all(); _log.error("Failed to reconnect: " + std::string(e.what())); on_websocket_disconnnect(); } @@ -123,6 +129,7 @@ DiscordCPP::Gateway::Gateway(std::string token, const std::shared_ptr lock(_reconnect_mutex); + _reconnect_finished.wait(lock, [this]() { + return !_reconnecting; + }); } diff --git a/Discord.C++/Gateway.h b/Discord.C++/Gateway.h index 05b9d34..6bd4670 100644 --- a/Discord.C++/Gateway.h +++ b/Discord.C++/Gateway.h @@ -4,6 +4,8 @@ #include #include #include +#include +#include #include #include "Logger.h" @@ -42,6 +44,10 @@ class Gateway { std::thread _heartbeat_task; /// indicator if Gateway is connected bool _connected; + /// condition to wait for ongoing reconnects + std::condition_variable _reconnect_finished; + std::mutex _reconnect_mutex; + bool _reconnecting; /// current sequence number unsigned int _sequence_number; /// logging instance diff --git a/Discord.C++/VoiceClient.cpp b/Discord.C++/VoiceClient.cpp index b76ffae..6160ea8 100644 --- a/Discord.C++/VoiceClient.cpp +++ b/Discord.C++/VoiceClient.cpp @@ -209,7 +209,6 @@ DiscordCPP::VoiceClient::VoiceClient(std::shared_ptr main_ws, DiscordCPP::VoiceClient::~VoiceClient() { _log.debug("~VoiceClient"); _ready = false; - disconnect(); _voice_ws->close(); } @@ -232,9 +231,11 @@ void DiscordCPP::VoiceClient::disconnect() { }; _voice_ws->close(); - _main_ws->send(payload).then([this]() { - _log.debug("Payload with Opcode 4 (Gateway Voice State Update) has been sent"); - }); + _main_ws->send(payload) + .then([this]() { + _log.debug("Payload with Opcode 4 (Gateway Voice State Update) has been sent"); + }) + .get(); } void DiscordCPP::VoiceClient::stop_playing() {