💓 Client keepalive: periodic ping/pong exchange for reliable connection failure detection
More...
💓 Client keepalive: periodic ping/pong exchange for reliable connection failure detection
The keepalive system uses a dedicated ping thread:
- Ping Thread: Sends periodic ping packets to server
- Response Monitoring: Server responds with pong packets
- Timeout Detection: Connection loss detected via failed pings
- Coordinated Shutdown: Thread integrates with global shutdown logic
Timing Strategy
Keepalive timing optimized for connection reliability:
- Ping Interval: 3 seconds between ping packets
- Server Timeout: Server times out clients after 5 seconds of silence
- Safety Margin: 2-second buffer prevents false disconnections
- Network Tolerance: Accounts for network jitter and processing delays
Thread Management
Ping thread follows robust lifecycle management:
- Creation: Thread started after successful connection
- Monitoring: Continuous health checks and connection validation
- Coordination: Respects global shutdown flags and connection state
- Termination: Graceful shutdown with resource cleanup
- Recovery: Thread recreated for each new connection
Connection Health Monitoring
Multiple layers of connection health detection:
- Socket Validity: Check socket file descriptor before sending
- Connection Flags: Monitor atomic connection state variables
- Send Failures: Detect network errors during ping transmission
- Global Shutdown: Respect application-wide shutdown requests
Integration Points
- main.c: Keepalive thread lifecycle management
- server.c: Ping packet transmission and connection monitoring
- protocol.c: Pong packet reception and response handling
- network.c: Low-level ping/pong packet formatting
Error Handling
Keepalive errors handled with appropriate escalation:
- Ping Send Failures: Signal connection loss for reconnection
- Socket Errors: Clean thread exit and connection cleanup
- Network Timeouts: Graceful handling without false alarms
- Thread Failures: Log errors and continue with degraded monitoring
Resource Management
Minimal resource usage for efficient keepalive:
- Thread Resources: Single lightweight thread with minimal stack
- Network Overhead: Small ping/pong packets with minimal bandwidth
- Timing Precision: Efficient sleep implementation with early wake
- Memory Usage: No dynamic allocations in steady-state operation
- Author
- Zachary Fogg me@zf.nosp@m.o.gg
- Date
- 2025
Definition in file keepalive.c.