首页 > 解决方案 > ASP.NET Core 3.1 SignalR 不会偶尔向 React 应用程序返回数据

问题描述

我正在使用 ASP.NET Core 3.1 和 React.js 构建一个应用程序,但是当我使用 SignalR 时,我onconnectedasync会向调用者返回可用锦标赛的列表。

问题是它工作了大约 5 次然后它停止了(只在前端显示微调器,我没有在控制台中获得一系列锦标赛)。

这是我的 ASP.NET Core SignalR 代码:

public class GameHub : Hub<IGameClient>
{
    private readonly ITournamentsStore _tournamentsStore;
    private readonly IMapper _mapper;

    public GameHub(ITournamentsStore tournamentsStore, IMapper mapper)
    {
        _tournamentsStore = tournamentsStore;
        _mapper = mapper;
    }

    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, "Not playing");

        var availableTournaments = _tournamentsStore.GetAvailableTournaments();
        var availableTournamentsDto = _mapper.Map<List<TournamentDto>>(availableTournaments);

        await Clients.Caller.ShowMainLobby(availableTournamentsDto);

        await base.OnConnectedAsync();
    }
}

反应代码:

import React, { useEffect, useState } from "react";
import { HubConnectionBuilder } from "@microsoft/signalr";
import Spinner from "../common/Spinner";
import MainLobby from "../gameParts/MainLobby";
import { connect } from "react-redux";
import { Redirect, useHistory } from "react-router";

const GamePage = ({ account }) => {
  const history = useHistory();
  const [conn, setConn] = useState(null);
  const [screen, setScreen] = useState("");
  const [tournaments, setTournaments] = useState(null);

  useEffect(() => {
     const newConn = new HubConnectionBuilder()
      .withUrl("/gameHub")
      .withAutomaticReconnect()
      .build();

  setConn(newConn);
   }, []);

  useEffect(() => {
    if (conn) {
      conn
        .start()
        .then((result) => {
          console.log("Connected");

      conn.on("ShowMainLobby", (tournaments) => {
        setTournaments(tournaments);
        console.log(tournaments);
        setScreen("ShowMainLobby");
      });
    })
    .catch((ex) => console.log("connection Failed: ", ex));
}
  }, [conn]);

  function returnToHomeMenu() {
    console.log(conn);
    conn.stop();
    history.push("/");
    console.log("disconnected");
}

  return !account.user.loggedIn ? (
    <Redirect to="/login" />
  ) : screen === "" ? (
    <>
       <Spinner text="Establishing Real Time Connection" />
    </>
   ) : screen === "ShowMainLobby" ? (
     <>
      <MainLobby
        tournaments={tournaments}
       returnToHomeMenu={returnToHomeMenu}
      />
    </>
   ) : (
   <></>
   );
  };

 function mapStateToProps(state) {
  return {
   account: state.account,
   };
 }

 export default connect(mapStateToProps)(GamePage);

任何帮助表示赞赏!

标签: reactjsasp.net-coresignalr

解决方案


推荐阅读