diff --git a/TODO.md b/TODO.md index 338e8a4..864c5af 100644 --- a/TODO.md +++ b/TODO.md @@ -2,7 +2,6 @@ ## Functionality -* Keepalives * Initial connection flag ## Unit Test Coverage @@ -12,6 +11,7 @@ * NetworkCommunication class * Dispatcher class * Storage incoming processing +* Keepalives * Notifiers * RPC * C++ API diff --git a/src/Dispatcher.cpp b/src/Dispatcher.cpp index fb43b2b..926b230 100644 --- a/src/Dispatcher.cpp +++ b/src/Dispatcher.cpp @@ -213,7 +213,9 @@ void DispatcherBase::DispatchThreadMain() { bool reconnect = false; for (auto& conn : m_connections) { // post outgoing messages if connection is active - if (conn->state() == NetworkConnection::kActive) conn->PostOutgoing(); + // only send keep-alives on client + if (conn->state() == NetworkConnection::kActive) + conn->PostOutgoing(!m_server); // if client, reconnect if connection died if (!m_server && conn->state() == NetworkConnection::kDead) diff --git a/src/NetworkConnection.cpp b/src/NetworkConnection.cpp index 4d5eefc..350a134 100644 --- a/src/NetworkConnection.cpp +++ b/src/NetworkConnection.cpp @@ -250,10 +250,18 @@ void NetworkConnection::QueueOutgoing(std::shared_ptr msg) { } } -void NetworkConnection::PostOutgoing() { +void NetworkConnection::PostOutgoing(bool keep_alive) { std::lock_guard lock(m_pending_mutex); - if (m_pending_outgoing.empty()) return; - m_outgoing.emplace(std::move(m_pending_outgoing)); - m_pending_outgoing.resize(0); - m_pending_update.resize(0); + auto now = std::chrono::steady_clock::now(); + if (m_pending_outgoing.empty()) { + if (!keep_alive) return; + // send keep-alives once a second (if no other messages have been sent) + if ((now - m_last_post) < std::chrono::seconds(1)) return; + m_outgoing.emplace(Outgoing{Message::KeepAlive()}); + } else { + m_outgoing.emplace(std::move(m_pending_outgoing)); + m_pending_outgoing.resize(0); + m_pending_update.resize(0); + } + m_last_post = now; } diff --git a/src/NetworkConnection.h b/src/NetworkConnection.h index e0b6267..bbfb083 100644 --- a/src/NetworkConnection.h +++ b/src/NetworkConnection.h @@ -9,6 +9,7 @@ #define NT_NETWORKCONNECTION_H_ #include +#include #include #include @@ -56,7 +57,7 @@ class NetworkConnection { NetworkStream& stream() { return *m_stream; } void QueueOutgoing(std::shared_ptr msg); - void PostOutgoing(); + void PostOutgoing(bool keep_alive); unsigned int uid() const { return m_uid; } @@ -95,6 +96,7 @@ class NetworkConnection { mutable std::mutex m_remote_id_mutex; std::string m_remote_id; std::atomic_ullong m_last_update; + std::chrono::steady_clock::time_point m_last_post; std::mutex m_pending_mutex; Outgoing m_pending_outgoing;