• SignalR主动通知订阅者示例


    html代码:

    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
    <script>
        $(function () {
            var hub = $.connection.payHub;
            hub.client.waitNotify = function (tran, url) {
                console.log("waitNotify:" + tran + "   " + url);
                if (tran) {
                    location.href = url;
                }
    
            };
            $.connection.hub.start().done(function () {
                console.log("hub done");
            });
        })
    </script>
    

    hub代码:

    [HubName("payHub"), Authorize]
        public class payHub : Hub
        {
            public static Dictionary<Guid, string> userPayHub = new Dictionary<Guid, string>();
            public static void Notify(Guid userId, string redirectUrl)
            {
                if (userPayHub.ContainsKey(userId))
                {
                    Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<Hubs.payHub>()
                       .Clients.Client(Hubs.payHub.userPayHub[userId])
                       .waitNotify(true, redirectUrl);
                }
            }
            public override Task OnConnected()
            {
                var uid = this.Context.User.Identity.GetUserId();
                userPayHub[uid] = this.Context.ConnectionId;
                return base.OnConnected();
            }
            public override Task OnDisconnected(bool stopCalled)
            {
                var uid = this.Context.User.Identity.GetUserId();
                userPayHub.Remove(uid);
                return base.OnDisconnected(stopCalled);
            }
            public override Task OnReconnected()
            {
                var uid = this.Context.User.Identity.GetUserId();
                userPayHub.Remove(uid);
                return base.OnReconnected();
            }
        }
    

    通知调用Notify方法即可。

    关键点:GlobalHost.ConnectionManager.GetHubContext

  • 相关阅读:
    LA 3135 优先队列
    uva 11991 查询中容器的运用
    uva 11995 判别数据类型
    LA 4973异面线段
    LA 2797 平面区域dfs
    LA 2218 半平面交
    poj 3525 求凸包的最大内切圆
    poj 1031 多边形对点(向周围发射光线)的覆盖
    poj 1269 直线间的关系
    kotlin学习笔记-异常好玩的list集合总结
  • 原文地址:https://www.cnblogs.com/calvinK/p/5345511.html
Copyright © 2020-2023  润新知