44 lines
include/tcp_client.h
Declares TcpClient, kMaxRetries, and the connect/reconnect contracts.
// TcpClient: persistent TCP connection with automatic reconnection.
#pragma once
#include <cstdint>
#include <string>
 
// Maximum reconnect attempts per reconnect() call.
static constexpr int kMaxRetries = 3;
 
// Manages a single outbound TCP connection with retry support.
class TcpClient {
public:
  TcpClient() = default;
  ~TcpClient();
 
  // Opens a TCP connection to host:port.
  // Parameters:
  //   host - remote hostname or IPv4 address
  //   port - remote TCP port
  // Returns: true if the TCP handshake completed.
  //   Sets isConnected() to true only after a successful handshake.
  //   On any failure, isConnected() remains false.
  bool connect(const std::string& host, uint16_t port);
 
  // Retries connect() using the last known host and port.
  // Parameters: none
  // Attempts exactly kMaxRetries reconnections.
  // Returns: true if any attempt succeeded within the retry budget
  bool reconnect();
 
  // Closes the connection and sets isConnected() to false.
  // Parameters: none
  // Returns: void; fd_ is closed and connected_ is set to false
  void disconnect();
 
  // Returns: true if a TCP handshake is currently established
  bool isConnected() const { return connected_; }
 
private:
  bool        connected_ = false;        // true only when a live TCP connection exists
  std::string host_;                     // remote hostname saved by connect()
  uint16_t    port_       = 0;           // remote port saved by connect()
  int         fd_         = -1;          // socket file descriptor; -1 when not open
  int         retriesLeft_ = kMaxRetries; // remaining reconnect attempts
};