websocket在React中多次连接

Posted

技术标签:

【中文标题】websocket在React中多次连接【英文标题】:websocket connecting multiple times in 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]);

【问题讨论】:

【参考方案1】:

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

类似这样的:

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

【讨论】:

非常感谢,每当我离开对话时关闭连接实际上是有意义的。

以上是关于websocket在React中多次连接的主要内容,如果未能解决你的问题,请参考以下文章

在 WebSocket 控制器中获取登录用户的 Principal

WebSocket简介

websocket._exceptions.WebSocketProxyException:通过代理连接失败状态:503

使用 stunnel 和 Ratchet 保护 websocket。连接已关闭

浅谈WebsocketAjax轮询和长连接(long pull)

WebSocket 实战