长连接断了不自动恢复,补心跳和退避重连

断线不重连,先补心跳和退避重连。

定时发 ping,两轮没回就主动 close。

重连按指数退避,1 秒起翻倍封顶 30 秒。

退避上叠随机抖动,别让客户端同时打。

连上后重置计数,重发订阅和鉴权。

页面切回前台时立即探活一次。

let retry = 0;
function connect(url) {
  const ws = new WebSocket(url);
  ws.onopen = () => {
    retry = 0;              // 连上就重置退避
    // 这里重发订阅、重新鉴权
  };
  ws.onclose = () => {
    const base = Math.min(30000, 1000 * 2 ** retry++);
    const delay = base / 2 + Math.random() * base / 2;  // 随机抖动
    setTimeout(() => connect(url), delay);
  };
  ws.onerror = () => ws.close();
  return ws;
}
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容