You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Socket.io断连容错实现:服务端disconnect事件触发时机咨询

Socket.io Disconnect Event Trigger Timing Explained

Great question—this is a common point of confusion with Socket.io's connection handling, so let's break it down simply:

1. When does the server's disconnect event fire?

The server's disconnect event does NOT trigger for short-lived outages (like a 1-second drop). It only fires after Socket.io's heartbeat timeout threshold is crossed.

Here's how the default heartbeat system works:

  • The server sends a ping packet to the client every 25 seconds (controlled by the pingInterval config).
  • The server waits 60 seconds (controlled by the pingTimeout config) for the client to send back a pong response.
  • If no pong is received within that combined window (effectively 85 seconds from the last successful communication), Socket.io marks the client as offline and triggers the disconnect event on the server.

Short blips (1 second, 5 seconds, even 20 seconds) won't trigger this—Socket.io's built-in reconnection logic kicks in automatically. The client will attempt to reconnect as soon as the network comes back up, and as long as it does so before the heartbeat timeout, the server won't register a disconnect.

2. Handling short outages without relying on disconnect

If you're worried about handling temporary drops, you don't need to wait for disconnect. Instead, you can listen to client-side events like:

  • reconnecting: Fires when the client starts attempting to reconnect after a drop.
  • reconnect: Fires when the client successfully reconnects.
  • reconnect_failed: Fires only if reconnection attempts fail beyond the heartbeat timeout (this is when the server will eventually trigger disconnect).

On the server side, you can also adjust the heartbeat timings if needed by modifying the config when initializing Socket.io:

const io = require('socket.io')(server, {
  pingInterval: 30000, // 30 seconds between pings
  pingTimeout: 60000   // 60 seconds to wait for pong
});

Just keep in mind that setting these values too low could lead to false disconnects if the network has minor latency spikes.

内容的提问来源于stack exchange,提问作者Adham Zahran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:56:52