ChatHub.cs 5.6 KB

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