ChatHub.cs 5.3 KB

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