网络抖动时需要心跳检测与指数退避重连。

本节要点

  • 定时发送 ping 保活
  • close 后延迟重连
  • 指数退避避免频繁请求

代码示例

let retry = 0

function connect() {
  const socket = new WebSocket("wss://example.com/ws")
  socket.onopen = () => { retry = 0 }
  socket.onclose = () => {
    const delay = Math.min(1000 * 2 ** retry++, 30000)
    setTimeout(connect, delay)
  }
}