乐闻世界logo
搜索文章和话题

How is the WebSocket heartbeat mechanism implemented?

2月18日 18:19

WebSocket heartbeat mechanism is used to detect connection activity and prevent connection disconnection due to network issues or timeouts.

Why Heartbeat is Needed

  1. Detect Connection Status: Timely detect if connection is disconnected
  2. Keep Connection Active: Prevent intermediate devices (such as firewalls, NAT) from closing connection due to long periods of no data transmission
  3. Fast Failure Recovery: Quickly reconnect after connection disconnection

Heartbeat Implementation Methods

Client Initiates Heartbeat

javascript
// Client sends heartbeat periodically const ws = new WebSocket('ws://example.com'); let heartbeatInterval; function startHeartbeat() { heartbeatInterval = setInterval(() => { if (ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'ping' })); } }, 30000); // Send every 30 seconds } function stopHeartbeat() { clearInterval(heartbeatInterval); } ws.onopen = startHeartbeat; ws.onclose = stopHeartbeat;

Server Responds to Heartbeat

javascript
// Server handles heartbeat wss.on('connection', (ws) => { ws.on('message', (message) => { const data = JSON.parse(message); if (data.type === 'ping') { ws.send(JSON.stringify({ type: 'pong' })); } }); });

Heartbeat Interval Settings

  • Recommended Interval: 30-60 seconds
  • Too Short: Increases server load and network traffic
  • Too Long: Cannot detect connection disconnection in time

Timeout Handling

javascript
let pongTimeout; const TIMEOUT = 5000; // 5 second timeout function sendPing() { ws.send(JSON.stringify({ type: 'ping' })); pongTimeout = setTimeout(() => { console.log('Heartbeat timeout, connection may be disconnected'); ws.close(); }, TIMEOUT); } ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'pong') { clearTimeout(pongTimeout); } };

Best Practices

  1. Bidirectional Heartbeat: Both client and server can initiate heartbeat
  2. Dynamic Adjustment: Dynamically adjust heartbeat interval based on network conditions
  3. Exponential Backoff: Use exponential backoff strategy when reconnecting
  4. Status Monitoring: Record heartbeat success/failure counts for monitoring connection quality
标签:WebSocket