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

React开发聊天室WebSocket刷新页面重复连接问题如何解决?

React WebSocket 刷新残留连接问题修复方案
  • 核心修复逻辑分为两部分:组件生命周期内的连接自动清理、页面卸载场景的主动断连处理
  • 修复后的完整代码如下:
useEffect(() => {
  if (!userInfo) {
    history.push("/login");
    return;
  }
  if (!(receiver_id && typeof receiver_id == "number")) return;

  const url = `ws://localhost:8000/ws/chat/${receiver_id}/?token=${userInfo.token}`;
  ws.current = new WebSocket(url);

  ws.current.onopen = function (event) {
    console.log("Connected");
    setConnected(true);
  };

  ws.current.onmessage = function (event) {
    console.log(event);
    console.log("Recieved");
    const dataFromServer = JSON.parse(event.data);
  };

  ws.current.onclose = function (event) {
    console.log("Disconnected");
    setConnected(false);
  };

  ws.current.onerror = function (event) {
    console.log("Something is not working, retry.");
  };

  // 监听页面刷新/关闭事件,主动发送断连请求
  const handlePageUnload = () => {
    if (ws.current) {
      // 1000为标准正常关闭状态码
      ws.current.close(1000, "User page refresh");
    }
  };
  window.addEventListener("beforeunload", handlePageUnload);

  // 组件卸载/依赖变更时的清理逻辑
  return () => {
    window.removeEventListener("beforeunload", handlePageUnload);
    if (ws.current) {
      ws.current.close(1000, "Component unmount");
      ws.current = null;
    }
  };
}, [receiver_id, history, userInfo]);
  • 改动说明:
    1. 将setConnected逻辑移入onopen回调,确保只有连接实际建立成功才标记为已连接,避免状态错位
    2. 新增beforeunload事件监听,用户触发F5刷新、关闭页面操作时,会主动向服务端发送正常关闭的帧,服务端会立即释放对应连接资源,不会产生残留无效连接
    3. 新增useEffect清理函数,当切换聊天对象(receiver_id变化)、用户登出(userInfo变化)、组件卸载时,都会主动关闭上一个WebSocket连接,避免同时存在多个有效连接
    4. 关闭连接时使用标准1000状态码,标识为正常主动关闭,服务端可区分异常断连和用户主动操作,方便后续重试逻辑扩展

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:27:01