ChatHub.cs 5.2 KB

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