【问题标题】:websocket connecting multiple times in Reactwebsocket在React中多次连接
【发布时间】:2021-08-21 19:45:26
【问题描述】:

我在 react 中使用 Websocket 构建了一个聊天应用程序,但是,每次我刷新页面 F5 时都会建立一个新连接。它完全按预期工作,但消耗的比应有的要多得多。 有没有办法在用户刷新页面时删除现有连接? (避免多个无用的连接)这里是我建立连接的地方:

  useEffect(() => {
    if (!userInfo) {
      history.push("/login");
    } else {
      if (receiver_id && typeof receiver_id == "number") {
        const url =
          "ws://localhost:8000" +
          "/ws/chat/" +
          receiver_id +
          "/?token=" +
          userInfo.token;
        ws.current = new WebSocket(url);
        if (!connected) {
          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");
        };

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

【问题讨论】:

    标签: reactjs websocket react-hooks use-effect


    【解决方案1】:

    您应该在清理功能中终止连接。

    类似这样的:

    return () => {
          ws.current.disconnect();
        };
    

    【讨论】:

    • 非常感谢,每当我离开对话时关闭连接实际上是有意义的。
    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 2022-01-13
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    相关资源
    最近更新 更多