简体   繁体   English

websocket 在反应中重新连接的最佳实践是什么?

[英]What is best practice to websocket reconnect in react?

I have react app with ticket polling (ticket is part of link for websocket connection).我已经通过票证轮询反应应用程序(票证是 websocket 连接的链接的一部分)。 Then I pass websocket object to another component, because only this (another) component should make .send() After user login or logout I need to get new ticket for new connection because server has specialized data for logged users.然后我将 websocket object 传递给另一个组件,因为只有这个(另一个)组件应该进行.send()用户登录或注销后我需要为新连接获取新票证,因为服务器具有用于登录用户的专用数据。 How should I organize my code for this task?我应该如何组织我的代码来完成这个任务?

I tried to reassign ws object after login/logout but got "Assignments to the 'ws' variable from inside React Hook useEffect will be lost after each render" error I can't store ws assignment inside useEffect hook because then i not be able to pass it as prop I'm although using Redux as you can see我尝试在登录/注销后重新分配 ws object 但得到“每次渲染后从 React Hook useEffect 内部分配给 'ws' 变量的分配将丢失”错误我无法将 ws 分配存储在 useEffect 挂钩中,因为那时我无法如您所见,尽管使用 Redux 将其作为道具传递

const App = () => {
  const { ticket, isLoggedIn } = useSelector(state => state);
  const dispatch = useDispatch();

  useEffect(() => {
    const requestTicket = () => {
      fetch('http://some/api/websocket', {
        method: 'POST'
      })
        .then(response => response.json())
        .then(ticket => {
          dispatch(setTicket(ticket));
        });
    };
    requestTicket();
  }, [dispatch]);

  let ws = new WebSocket('ws://socket/' + ticket);

  useEffect(() => {
    fetch('http://some/api/websocket', {
      method: 'POST'
    })
      .then(response => response.json())
      .then(ticket => {
        ws = new WebSocket('ws://socket/' + ticket);
      });
  }, [isLoggedIn, ws]);

  ws.onmessage = e => {
    dispatch(setData(JSON.parse(e.data)));
  };

  return <Child ws={ws} />;
};

Wrap WebSocket connection and onmessage in a function.将 WebSocket 连接和 onmessage 包装在 function 中。 check if WebSocket is close, callback the function.检查WebSocket是否关闭,回调function。 Also may use setTimeout.也可以使用 setTimeout。 Example:例子:

function connect(){
  //WebSocket Connection
  //WebSocket onmessage
}
conn.onclose = evt => {
console.log('Socket is closed.Reconnect will be attempted in 10 second.', evt.reason);
    setTimeout(() => connect(), 10000);
};

I'm using this way我正在使用这种方式

function connect() {
  var ws = new WebSocket('ws://localhost:8080');
  ws.onopen = function() {
    // subscribe to some channels
    ws.send(JSON.stringify({
        //.... some message the I must send when I connect ....
    }));
  };

  ws.onmessage = function(e) {
    console.log('Message:', e.data);
  };

  ws.onclose = function(e) {
    console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
    setTimeout(function() {
      connect();
    }, 1000);
  };

  ws.onerror = function(err) {
    console.error('Socket encountered error: ', err.message, 'Closing socket');
    ws.close();
  };
}

connect();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM