要重定向的 SignalR 自定义方法

SignalR custom method to redirect

本文关键字:自定义方法 SignalR 重定向      更新时间:2023-09-26

我已经制作了 SignalR 自定义方法,如果用户想加入已经有 2 个成员的组,可以重定向用户。除了重定向方法外,一切似乎都工作正常。

聊天中心.cs:

namespace SignalRChat
{
    public class ChatHub : Hub
    {
        static string test2 = "";
        public static Dictionary<string, int> rooms = new Dictionary<string, int>();
        public void Test(string groupName)
        {
            if (!rooms.ContainsKey(groupName))
            {
                rooms.Add(groupName, 1);
            }
            else if(rooms[groupName] != 2)
            {
                rooms[groupName] = 2;
            }
            else
            {
                test2 = "testing";
                Redirect();
            }
        }
        public Task Redirect()
        {
            return Clients.Caller.redirectTo();
        }
        public Task JoinGroup(string groupName)
        { 
            return Groups.Add(Context.ConnectionId, groupName); 
        }
    }
}

脚本:

var chat2 = $.connection.chatHub;
$.connection.hub.start().done(function () {
    chat2.server.test(roomId);
    chat2.client.redirectTo = function () {
        window.location.replace("http://stackoverflow.com");
    }
    chat2.server.joinGroup(roomId);
});

当组中已有 2 个客户端时,test2 设置为"测试",但客户端不会被重定向。

将脚本更改为:

var chat2 = $.connection.chatHub;
// var roomId = "R1" <-- I added this for testing
chat2.client.redirectTo = function () {
    window.location.replace("http://stackoverflow.com/questions/35848709/signalr-custom-method-to-redirect#35857376");
}
$.connection.hub.start().done(function () {
    chat2.server.joinGroup(roomId);
    chat2.server.test(roomId);
});

注意:在您的Test方法中,逻辑表明仅当字典包含给定的房间名并且与该房间名对应的 int 值为"2"时rooms重定向才会运行。可能不是你真正计划的逻辑。

为了进行测试,我添加到支持的代码中:

  public static Dictionary<string, int> rooms = new Dictionary<string, int>();
  public void Test(string groupName) // <-- I sent "groupName: R1" from js 
     {
        rooms["R1"] = 2;
        if ...
     }