From cd7b439f4c70230fa88f84843a23468e399d6029 Mon Sep 17 00:00:00 2001 From: "Matthias P. Braendli" Date: Wed, 4 Dec 2024 08:41:09 +0100 Subject: common: Update Socket --- contrib/Socket.cpp | 19 +++++++++++++++---- contrib/Socket.h | 6 +++++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/contrib/Socket.cpp b/contrib/Socket.cpp index a85b98b..938b573 100644 --- a/contrib/Socket.cpp +++ b/contrib/Socket.cpp @@ -478,7 +478,7 @@ TCPSocket::~TCPSocket() TCPSocket::TCPSocket(TCPSocket&& other) : m_sock(other.m_sock), - m_remote_address(move(other.m_remote_address)) + m_remote_address(std::move(other.m_remote_address)) { if (other.m_sock != -1) { other.m_sock = -1; @@ -967,12 +967,22 @@ ssize_t TCPClient::recv(void *buffer, size_t length, int flags, int timeout_ms) reconnect(); } + m_last_received_packet_ts = chrono::steady_clock::now(); + return ret; } catch (const TCPSocket::Interrupted&) { return -1; } catch (const TCPSocket::Timeout&) { + const auto timeout = chrono::milliseconds(timeout_ms * 5); + if (m_last_received_packet_ts.has_value() and + chrono::steady_clock::now() - *m_last_received_packet_ts > timeout) + { + // This is to catch half-closed TCP connections + reconnect(); + } + return 0; } @@ -983,6 +993,7 @@ void TCPClient::reconnect() { TCPSocket newsock; m_sock = std::move(newsock); + m_last_received_packet_ts = nullopt; m_sock.connect(m_hostname, m_port, true); } @@ -990,7 +1001,7 @@ TCPConnection::TCPConnection(TCPSocket&& sock) : queue(), m_running(true), m_sender_thread(), - m_sock(move(sock)) + m_sock(std::move(sock)) { #if MISSING_OWN_ADDR auto own_addr = m_sock.getOwnAddress(); @@ -1109,7 +1120,7 @@ void TCPDataDispatcher::process() auto sock = m_listener_socket.accept(timeout_ms); if (sock.valid()) { auto lock = unique_lock(m_mutex); - m_connections.emplace(m_connections.begin(), move(sock)); + m_connections.emplace(m_connections.begin(), std::move(sock)); if (m_buffers_to_preroll > 0) { for (const auto& buf : m_preroll_queue) { @@ -1181,7 +1192,7 @@ void TCPReceiveServer::process() } else { buf.resize(r); - m_queue.push(make_shared(move(buf))); + m_queue.push(make_shared(std::move(buf))); } } catch (const TCPSocket::Interrupted&) { diff --git a/contrib/Socket.h b/contrib/Socket.h index ab2a14a..7709145 100644 --- a/contrib/Socket.h +++ b/contrib/Socket.h @@ -31,9 +31,11 @@ #include "ThreadsafeQueue.h" #include #include -#include +#include #include #include +#include +#include #include #include @@ -236,6 +238,8 @@ class TCPClient { TCPSocket m_sock; std::string m_hostname; int m_port; + + std::optional m_last_received_packet_ts; }; /* Helper class for TCPDataDispatcher, contains a queue of pending data and -- cgit v1.2.3