Signalr 信号员需要以游戏ID的特定游戏为目标,而不是所有现场游戏

Signalr 信号员需要以游戏ID的特定游戏为目标,而不是所有现场游戏,signalr,signalr-hub,signalr.client,signalr-2,Signalr,Signalr Hub,Signalr.client,Signalr 2,我没有想到这一点,但这段代码正在向所有客户发送游戏模型。我需要使用此控制器操作中的GameID,并且只针对观看该游戏的客户。我该怎么做 发布控制器操作 public UpdateGameResponse UpdateGame(int gameId) { ... var model = Game.Create(XDocument.Load(httpRequest.Files[0].InputStream)).Parse(); GlobalHost.Con

我没有想到这一点,但这段代码正在向所有客户发送游戏模型。我需要使用此控制器操作中的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));

}
客户端

  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或创建组。 注意:为了使用连接Id解决方案,每个GameID必须有自己到集线器的连接

我更喜欢根据个人经验使用小组,但任何一种方法都可以

要在中心中创建组,需要在中心类中创建一个方法。

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()));
在您的情况下,您可以将gameID设置为
groupname
,然后调用
GlobalHost.ConnectionManager.GetHubContext().Clients.Groups(gameID).receiveUpdates(Newtonsoft.Json.JsonConvert.SerializedObject(model))

检索连接Id:

var _connectionId = $.connection.hub.id;
然后将连接Id发送到服务器, 然后继续使用调用
GlobalHost.ConnectionManager.GetHubContext().Clients.Clients.Client(_connectionId).receiveUpdates(Newtonsoft.Json.JsonConvert.SerializeObject(model))
调用该特定连接

var _connectionId = $.connection.hub.id;