【问题标题】:SignalR needs to target specific games with Game ID and not all live gamesSignalR 需要针对具有游戏 ID 的特定游戏而不是所有实时游戏
【发布时间】:2018-07-13 22:44:48
【问题描述】:

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

【问题讨论】:

    标签: signalr signalr-hub signalr.client signalr-2


    【解决方案1】:

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

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

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

    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&lt;GameCastHub&gt;().Clients.Groups(gameID).receiveUpdates(Newtonsoft.Json.JsonConvert.SerializeObject(model));

    检索连接 ID:

    var _connectionId = $.connection.hub.id;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      相关资源
      最近更新 更多