SignalR 需要针对具有游戏 ID 的特定游戏而不是所有实时游戏

SignalR needs to target specific games with Game ID and not all live games

我没想到这一点,但这段代码正在将游戏模型发送给所有客户端。我需要使用此控制器操作中的 GameID,并且只针对观看该游戏的客户。我该怎么做?

发布控制器操作

public UpdateGameResponse UpdateGame(int gameId)
        {

...

 var model = Game.Create(XDocument.Load(httpRequest.Files[0].InputStream)).Parse();


         GlobalHost.ConnectionManager.GetHubContext<GameCastHub>().Clients.All.receiveUpdates(Newtonsoft.Json.JsonConvert.SerializeObject(model));

}

中心

 [HubName("gamecastHub")]
    public class GameCastHub : Hub
    {
    }

客户端

  var connected = false;
                var gamecastHub = $.connection.gamecastHub;

                if (gamecastHub) {

                    gamecastHub.client.receiveUpdates = function (updates) {
                        console.log('New updates received');
                        processUpdates(updates);
                    };

                    connectLiveUpdates();

                    $.connection.hub.connectionSlow(function () {
                        console.log('Live updates connection running slow');
                    });

                    $.connection.hub.disconnected(function () {
                        connected = false;
                        console.log('Live updates disconnected');
                        setTimeout(connectLiveUpdates, 10000);
                    });

                    $.connection.hub.reconnecting(function () {
                        console.log('Live updates reconnecting...');
                    });

                    $.connection.hub.reconnected(function () {
                        connected = false;
                        console.log('Live updates reconnected');
                    });
                }

我建议使用与集线器的每个连接关联的连接 ID 或创建组。 注意:每个 GameID 必须有自己的连接到集线器才能使用连接 Id 解决方案。

根据个人经验,我更喜欢使用群组,但两种方式都可以。

要在中心创建组,您需要在中心创建方法 class。

public async void setGroup(string groupName){
    await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}

其次,在客户端需要一个JS函数来调用hub函数。

$.connection.hub.invoke("setGroup", groupName).catch(err => console.error(err.toString()));

在您的情况下,您可以将游戏 ID 设为 groupname,然后调用 GlobalHost.ConnectionManager.GetHubContext<GameCastHub>().Clients.Groups(gameID).receiveUpdates(Newtonsoft.Json.JsonConvert.SerializeObject(model));

获取连接ID:

var _connectionId = $.connection.hub.id;

然后将connection Id发送给服务器, 并继续使用调用 GlobalHost.ConnectionManager.GetHubContext<GameCastHub>().Clients.Clients.Client(_connectionId).receiveUpdates(Newtonsoft.Json.JsonConvert.SerializeObject(model)); 来调用该特定连接。