ChatHub.cs 5.2 KB

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