设为首页 加入收藏

TOP

.net core 3.0 Signalr - 07 业务实现-服务端 自定义管理组、用户、连接(一)
2019-10-09 19:59:20 】 浏览:117
Tags:.net core 3.0 Signalr 业务 实现 服务 定义 管理 用户 连接

Hub的管理

  • 重写OnConnectedAsync
    从连接信息中获取UserId、Groups,ConnectId,并实现这三者的关系,存放于redis中
    代码请查看

    using CTS.Signalr.Server.Cores;
    using CTS.Signalr.Server.Dtos;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.SignalR;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace CTS.Signalr.Server.Hubs
    {
        /// <summary>
        /// 服务端接口
        /// </summary>
        public interface IServerNotifyHub
        {
    
        }
    
        /// <summary>
        /// 客户端使用的接口
        /// </summary>
        public interface IClientNotifyHub
        {
            Task OnNotify(object data);
    
            Task OnLine(object data);
    
            Task OffLine(object data);
        }
    
    
        [Authorize]
        public class NotifyHub : Hub<IClientNotifyHub>,IServerNotifyHub
        {
            private readonly SignalrRedisHelper _signalrRedisHelper;
            private readonly ILogger _logger;
    
            public NotifyHub(SignalrRedisHelper signalrRedisHelper, ILogger<NotifyHub> logger)
            {
                _signalrRedisHelper = signalrRedisHelper;
                _logger = logger;
            }
    
            public override async Task OnConnectedAsync()
            {
                //await Clients.All.OnNotify(new { UserId= Context.User.Identity.Name, Name=Context.User.Identity.Name, ConnectId = Context.ConnectionId });
                var userId= Context.User.Identity.Name;
                var groups=Context.GetHttpContext().Request.Query["group"].FirstOrDefault();
                _logger.LogDebug($"OnConnectedAsync----userId:{userId},groups:{groups},connectionId:{ Context.ConnectionId}");
                if (!string.IsNullOrWhiteSpace(userId))
                {
                    await _signalrRedisHelper.AddConnectForUserAsync(userId, Context.ConnectionId);
                    await JoinToGroup(userId, Context.ConnectionId, groups?.Split(','));
                    await DealOnLineNotify(userId, Context.ConnectionId);
                }
                await base.OnConnectedAsync();
            }
    
            public override async Task OnDisconnectedAsync(Exception exception)
            {
                var userId = Context.User.Identity.Name;
                var groups = Context.GetHttpContext().Request.Query["group"].FirstOrDefault();
                _logger.LogDebug($"OnDisconnectedAsync----userId:{userId},groups:{groups},connectionId:{ Context.ConnectionId}");
                if (!string.IsNullOrWhiteSpace(userId))
                {
                    await _signalrRedisHelper.RemoveConnectForUserAsync(userId, Context.ConnectionId);
                    await DealOffLineNotify(userId,Context.ConnectionId);
                }
                await LeaveFromGroup(Context.ConnectionId, groups?.Split(','));
                await base.OnDisconnectedAsync(exception);
            }
    
            /// <summary>
            /// 加入组
            /// </summary>
            /// <param name="groupName"></param>
            /// <returns></returns>
            private async Task JoinToGroup(string userId,string connectionId,params string[] groups)
            {
                if (!string.IsNullOrWhiteSpace(userId)&& groups!=null&&groups.Length>0)
                {
                    foreach (var group in groups)
                    {
                        await Groups.AddToGroupAsync(connectionId, group);
                        await _signalrRedisHelper.AddUserForGroupAsync(group, connectionId, userId);
    
                        // await Clients.Group(group).OnJoinGroup(new { ConnectId = connectionId, UserId = userId, GroupName = group });
                    }
                }
            }
    
            /// <summary>
            /// 从组中移除
            /// </summary>
            /// <param name="groupName"></param>
            /// <returns></returns>
            private async Task LeaveFromGroup(string connectionId,params string[] groups)
            {
                if (groups !=
首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇.net core 3.0 Signalr - 05 使用.. 下一篇.net core 3.0 Signalr - 09 待改..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目