Search code examples
asp.net-core.net-coresignalrasp.net-core-signalr

How to use Game Loops to Trigger SignalR Group Messages?


Background

I have built a game on top of SignalR in .NET framework and am now porting to dotnet core. As part of this I have several "Game Rooms" with up to 6 players in each. I am using SignalR's Group functionality to support the concept of GameRoom - no problems there.

The Question

My question, how do I enable each GameRoom to broadcast messages automatically every 5 seconds to all members of the group?

I have one GameHub.cs which has a List<GameRoom>. Each GameRoom then maintains all the data (scores, players, SignalR users, SignalR group name, etc) for it's corresponding game. Inside the Game Room I have a Game Loop which I want to leverage to push data to the players. The Game Rooms are static for the duration of the game.

I am unable to ascertain if my dependency modelling is correct in the new dotnet core world. For example: GameHub --> GameRoom which in turn contains a simple Timer loop. Inside this timer I don't know how to call GameHub to broadcast messages.

In .NET I could leverage GlobalHost to get the GameHub and broadcast a group message something like this was ok, how does one do something similar for dot-net core implementation? How to use game loops to trigger SignalR group messages?

class GameRoom
{
    List<player> _players;
    Scoreboard _scores;
    string _gameRoomName;
    ...
    void GameLoop_Timer_Elapsed(object sender, ElapsedEventArgs e) 
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<Game>();
        context.Clients.Group(_gameRoomName).SendMessage(_gameState);
    }
}

Solution

  • Inside Asp.net core, I suggest you could use backgroud service to achieve your requirement. Inside the backrround service you could write the logic to call the hub to send the group message every 5 seconds.

    For how to call the ihubcontext, you could refer to this article and this sample.

    For how to use background service, you could refer to this article.