ChatHub.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. using Microsoft.AspNetCore.SignalR;
  2. using NPOI.SS.Formula.Functions;
  3. using OASystem.API.OAMethodLib.Hub;
  4. using OASystem.API.OAMethodLib.Hub.HubClients;
  5. using OASystem.API.OAMethodLib.SignalR.Hubs;
  6. using OASystem.API.OAMethodLib.SignalR.HubService;
  7. using Quartz;
  8. using SqlSugar.DistributedSystem.Snowflake;
  9. using System.DirectoryServices.Protocols;
  10. using System.Text.RegularExpressions;
  11. using static OASystem.API.OAMethodLib.Hub.Hubs.ChatHub;
  12. using static OASystem.API.OAMethodLib.JWTHelper;
  13. namespace OASystem.API.OAMethodLib.Hub.Hubs
  14. {
  15. //[Authorize]
  16. [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
  17. public class ChatHub : Hub<IChatClient>
  18. {
  19. private readonly ILogger<ChatHub> _logger;
  20. private readonly CommonService _common;
  21. /// <summary>
  22. /// 已登录的用户信息
  23. /// </summary>
  24. //public static List<UserModel> OnlineUser { get; set; } = new List<UserModel>();
  25. public ChatHub(ILogger<ChatHub> logger, CommonService common)
  26. {
  27. _logger = logger;
  28. _common = common;
  29. }
  30. /// <summary>
  31. /// SignalR登录验证
  32. /// </summary>
  33. public async Task SignalRLogin(int userId)
  34. {
  35. string connid = Context.ConnectionId;
  36. string result = $"[{connid}]";
  37. string userId1 = Context.UserIdentifier;
  38. if (!UserStore.OnlineUser.Exists(u => u.ConnectionId == connid))
  39. {
  40. result += "上线成功!" ;
  41. UserStore.OnlineUser.Add( new UserModel() { UserId = userId,ConnectionId = connid,GroupName = "FMGJ-OASystem" });
  42. }
  43. else
  44. {
  45. result += "已上线!";
  46. }
  47. //给当前连接返回消息
  48. await Clients.Client(connid).SendAsync("SignalRLoginResponse", result);
  49. }
  50. /// <summary>
  51. /// 客户端连接服务端
  52. /// </summary>
  53. /// <returns></returns>
  54. public override Task OnConnectedAsync()
  55. {
  56. var httpContext = Context.GetHttpContext();
  57. if (httpContext != null)
  58. {
  59. string token = httpContext.Request.Headers["Authorization"]; // 根据实际情况修改 header key
  60. // 处理 token...
  61. if (!string.IsNullOrEmpty(token))
  62. {
  63. TokenModelJwt tokenModelJwt = JwtHelper.SerializeJwt(token.ToString().Split(" ")[1]);
  64. string result = "";
  65. if (tokenModelJwt != null)
  66. {
  67. var connId = Context.ConnectionId;
  68. UserStore.OnlineUser.Add(new UserModel() { UserId = tokenModelJwt.UserId, ConnectionId = connId, GroupName = "FMGJ-OASystem" });
  69. _logger.LogInformation($"Client ConnectionId=> [[{connId}]] UserId=> [[{tokenModelJwt.UserId}]] Already Connection Server!");
  70. //Clients.All.SendAsync("GetOnlineResponse", $"[{tokenModelJwt.UserName}({tokenModelJwt.Role})] 上线");
  71. Clients.Clients(connId).ReceiveMessage(_common.ReceiveMessage($"[{tokenModelJwt.UserName}({tokenModelJwt.Role})] 已上线!"));
  72. //
  73. }
  74. }
  75. }
  76. //给当前连接返回消息
  77. //await Clients.Client(connid).SendAsync("SignalRLoginResponse", result);
  78. return base.OnConnectedAsync();
  79. }
  80. /// <summary>
  81. /// 客户端断开连接
  82. /// </summary>
  83. /// <param name="exception"></param>
  84. /// <returns></returns>
  85. public override Task OnDisconnectedAsync(Exception exception)
  86. {
  87. var connId = Context.ConnectionId;
  88. _logger.LogInformation($"Client ConnectionId=> [[{connId}]] Already Close Connection Server!");
  89. var model = UserStore.OnlineUser.Find(u => u.ConnectionId == connId);
  90. int count = UserStore.OnlineUser.RemoveAll(u => u.ConnectionId == connId);
  91. if (model != null)
  92. {
  93. var onlineUser = UserStore.OnlineUser.FindAll(u => u.GroupName == model.GroupName);
  94. Clients.Clients(connId).ReceiveMessage(_common.ReceiveMessage($"[UserID=>{model.UserId} ConnectionId=> {model.ConnectionId} ] 已下线!"));
  95. }
  96. return base.OnDisconnectedAsync(exception);
  97. }
  98. /**
  99. * 测试
  100. * */
  101. /// <summary>
  102. /// 给所有客户端发送消息
  103. /// </summary>
  104. /// <returns></returns>
  105. public async Task SendMessage(string data)
  106. {
  107. Console.WriteLine("Have one Data!");
  108. await Clients.All.SendAll(_common.SendAll(data));
  109. await Clients.Caller.SendAll(_common.SendCaller(data));
  110. }
  111. /// <summary>
  112. /// 发送消息给指定用户(系统)
  113. /// </summary>
  114. /// <param name="id"></param>
  115. /// <param name="message"></param>
  116. /// <returns></returns>
  117. public async Task SendSystemToUser(string id, string message) => await Clients.Client(id).SendAsync("ReceiveMessage", message);
  118. /// <summary>
  119. /// 发送消息给所有用户(系统)
  120. /// </summary>
  121. /// <param name="id"></param>
  122. /// <param name="message"></param>
  123. /// <returns></returns>
  124. public async Task SendSystemToAllUser(string message) => await Clients.All.SendAsync("ReceiveMessage", message);
  125. }
  126. }