using Microsoft.AspNetCore.SignalR; using OASystem.API.OAMethodLib.Hub; using OASystem.API.OAMethodLib.Hub.HubClients; using OASystem.API.OAMethodLib.SignalR.Hubs; using OASystem.API.OAMethodLib.SignalR.HubService; using System.DirectoryServices.Protocols; using System.Text.RegularExpressions; using static OASystem.API.OAMethodLib.Hub.Hubs.ChatHub; using static OASystem.API.OAMethodLib.JWTHelper; namespace OASystem.API.OAMethodLib.Hub.Hubs { public class ChatHub : Hub { private readonly ILogger _logger; private readonly CommonService _common; /// /// 已登录的用户信息 /// //public static List OnlineUser { get; set; } = new List(); public ChatHub(ILogger logger, CommonService common) { _logger = logger; _common = common; } /// /// SignalR登录验证 /// public async Task SignalRLogin(int userId) { string connid = Context.ConnectionId; string result = $"[{connid}]"; if (!UserStore.OnlineUser.Exists(u => u.ConnectionId == connid)) { result += "上线成功!" ; UserStore.OnlineUser.Add( new UserModel() { UserId = userId,ConnectionId = connid,GroupName = "FMGJ-OASystem" }); } else { result += "已上线!"; } //给当前连接返回消息 await Clients.Client(connid).SendAsync("SignalRLoginResponse", result); } /// /// 客户端连接服务端 /// /// public override Task OnConnectedAsync() { var connid = Context.ConnectionId; _logger.LogInformation($"Client ConnectionId=> [[{connid}]] Already Connection Server!"); return base.OnConnectedAsync(); } /// /// 客户端断开连接 /// /// /// public override Task OnDisconnectedAsync(Exception exception) { var connid = Context.ConnectionId; _logger.LogInformation($"Client ConnectionId=> [[{connid}]] Already Close Connection Server!"); var model = UserStore.OnlineUser.Find(u => u.ConnectionId == connid); int count = UserStore.OnlineUser.RemoveAll(u => u.ConnectionId == connid); if (model != null) { var onlineUser = UserStore.OnlineUser.FindAll(u => u.GroupName == model.GroupName); Clients.Group(model.GroupName).SendAsync("GetUsersResponse", onlineUser); } return base.OnDisconnectedAsync(exception); } /** * 测试 * */ /// /// 给所有客户端发送消息 /// /// public async Task SendMessage(string data) { Console.WriteLine("Have one Data!"); await Clients.All.SendAll(_common.SendAll(data)); await Clients.Caller.SendAll(_common.SendCaller(data)); } } }