ChatHub.cs 5.4 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. Clients.Clients(connId).ReceiveMessage(_common.ReceiveMessage($"[{tokenModelJwt.UserName}({tokenModelJwt.Role})] 已上线!"));
  71. //
  72. }
  73. }
  74. }
  75. //给当前连接返回消息
  76. //await Clients.Client(connid).SendAsync("SignalRLoginResponse", result);
  77. return base.OnConnectedAsync();
  78. }
  79. /// <summary>
  80. /// 客户端断开连接
  81. /// </summary>
  82. /// <param name="exception"></param>
  83. /// <returns></returns>
  84. public override Task OnDisconnectedAsync(Exception exception)
  85. {
  86. var connId = Context.ConnectionId;
  87. _logger.LogInformation($"Client ConnectionId=> [[{connId}]] Already Close Connection Server!");
  88. var model = UserStore.OnlineUser.Find(u => u.ConnectionId == connId);
  89. int count = UserStore.OnlineUser.RemoveAll(u => u.ConnectionId == connId);
  90. if (model != null)
  91. {
  92. var onlineUser = UserStore.OnlineUser.FindAll(u => u.GroupName == model.GroupName);
  93. Clients.Clients(connId).ReceiveMessage(_common.ReceiveMessage($"[UserID=>{model.UserId} ConnectionId=> {model.ConnectionId} ] 已下线!"));
  94. }
  95. return base.OnDisconnectedAsync(exception);
  96. }
  97. /**
  98. * 测试
  99. * */
  100. /// <summary>
  101. /// 给所有客户端发送消息
  102. /// </summary>
  103. /// <returns></returns>
  104. public async Task SendMessage(string data)
  105. {
  106. Console.WriteLine("Have one Data!");
  107. await Clients.All.SendAll(_common.SendAll(data));
  108. await Clients.Caller.SendAll(_common.SendCaller(data));
  109. }
  110. /// <summary>
  111. /// 发送消息给指定用户(系统)
  112. /// </summary>
  113. /// <param name="id"></param>
  114. /// <param name="message"></param>
  115. /// <returns></returns>
  116. public async Task SendSystemToUser(string id, string message) => await Clients.Client(id).SendAsync("ReceiveMessage", message);
  117. /// <summary>
  118. /// 发送消息给所有用户(系统)
  119. /// </summary>
  120. /// <param name="id"></param>
  121. /// <param name="message"></param>
  122. /// <returns></returns>
  123. public async Task SendSystemToAllUser(string message) => await Clients.All.SendAsync("ReceiveMessage", message);
  124. }
  125. }