SignalR 在 React 中通过连接发送消息

问题描述 投票:0回答:1

我有一个具有 SignalR 连接的 React 应用程序。在 useEffect 函数中建立连接,然后连接到服务器。一旦建立连接,客户端就会向服务器发送一条消息,以便加入一个组来接收消息。我在连接上有 withAutomaticReconnect 方法。问题是,如果连接中断并且确实重新连接,则工作正常。但是,我在初始连接时向服务器发送消息的方法不会再次运行,因此即使重新建立客户端-服务器连接,也不会再次发送消息方法。我的问题是,如何设置连接以在连接时自动向服务器发送消息?

这是代码:

  const [connection, setConnection] = useState(null);

 // Create connection with server
  useEffect(() => {
    const hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(`${process.env.REACT_APP_API_URL}/hubs/hub`, {
        withCredentials: false,
        accessTokenFactory: () => {
          // Get and return the access token.
          // This function can return a JavaScript Promise if asynchronous
          // logic is required to retrieve the access token.

          return getSessionAccessToken();
        },
      })
      .withAutomaticReconnect()
      .build();

    setConnection(hubConnection);
    const startConnection = async () => {
      try {
        await hubConnection.start();
      } catch (error) {
        const toastInfo = {
          description: HUB_CONNECTION_ERROR_MESSAGE,
          type: TOAST_TYPES.error,
        };
        dispatch(addToast(toastInfo));
      }
      try {
      // ======================== This function below needs to run every initial connection and every reconnection.  Currently this isn't run on reconnection, which is expected but I am not sure how to add that to the hubConnection itself ========================
        await hubConnection.send(HUB_CONNECTION_TYPES.ADD_USER_TO_GROUP, {
          groupId: groupId,
        });
      } catch (error) {
        const toastInfo = {
          description: HUB_CONNECTION_ERROR_MESSAGE,
          type: TOAST_TYPES.error,
        };
        dispatch(addToast(toastInfo));
      }
    };
    startConnection();
  }, [groupId, dispatch]);

  // Functions to be run based on connection server actions
  useEffect(() => {
    if (connection) {
      connection.on(
        HUB_CONNECTION_TYPES.RECEIVING_MESSAGE,
        (message) => {
          dispatch(function(message.receivingMessage));
        }
      );
    }

    // Returns in useEffect functions run when the component dismounts (e.g. leaving the page)
    return async () => {
      if (connection) {
        await connection.send(HUB_CONNECTION_TYPES.REMOVE_USER_FROM_GROUP, {
          groupId: groupId,
        });
        connection.stop();
      }
    };
  }, [connection, groupId, dispatch]);
reactjs signalr
1个回答
0
投票

我找到了这个场景的答案。连接上有一个方法,如果发生重新连接,可以调用该方法: hubConnection.onreconnected(callback function)

© www.soinside.com 2019 - 2024. All rights reserved.