新增系统通知实时通知给连接的客户端

This commit is contained in:
不做码农
2022-03-01 14:04:21 +08:00
parent 06b81d5f5e
commit 267469dc55
11 changed files with 148 additions and 38 deletions

View File

@@ -1,13 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Constant;
using Infrastructure.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using ZR.Admin.WebApi.Filters;
using ZR.Model;
using ZR.Service.System.IService;
namespace ZR.Admin.WebApi.Hubs
{
@@ -15,6 +14,20 @@ namespace ZR.Admin.WebApi.Hubs
{
//创建用户集合,用于存储所有链接的用户数据
private static readonly List<OnlineUsers> clientUsers = new();
private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private ISysNoticeService SysNoticeService;
public MessageHub(ISysNoticeService noticeService)
{
SysNoticeService = noticeService;
}
private ApiResult SendNotice()
{
var result = SysNoticeService.GetSysNotices();
return new ApiResult(200, "success", result);
}
#region
@@ -25,16 +38,18 @@ namespace ZR.Admin.WebApi.Hubs
public override Task OnConnectedAsync()
{
var name = Context.User.Identity.Name;
var user = clientUsers.Any(u => u.ConnnectionId == Context.ConnectionId);
//判断用户是否存在,否则添加集合
if (!user && Context.User.Identity.IsAuthenticated)
{
clientUsers.Add(new OnlineUsers(Context.ConnectionId, name));
Console.WriteLine($"{DateTime.Now}{name},{Context.ConnectionId}连接服务端success当前已连接{clientUsers.Count}个");
Clients.All.SendAsync("welcome", $"欢迎您:{name},当前时间:{DateTime.Now}");
Clients.All.SendAsync(HubsConstant.MoreNotice, SendNotice());
}
Clients.All.SendAsync("onlineNum", clientUsers.Count);
Clients.All.SendAsync(HubsConstant.OnlineNum, clientUsers.Count);
return base.OnConnectedAsync();
}
@@ -50,7 +65,7 @@ namespace ZR.Admin.WebApi.Hubs
{
Console.WriteLine($"用户{user?.Name}离开了,当前已连接{clientUsers.Count}个");
clientUsers.Remove(user);
Clients.All.SendAsync("onlineNum", clientUsers.Count);
Clients.All.SendAsync(HubsConstant.OnlineNum, clientUsers.Count);
}
return base.OnDisconnectedAsync(exception);
}