| | |
| | | private readonly IHttpContextAccessor _httpContextAccessor; |
| | | private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(ChatHub)); |
| | | ILogger<ChatHub> _logger; |
| | | |
| | | public ChatHub(ILogger<ChatHub> logger, IHttpContextAccessor httpContextAccessor) |
| | | { |
| | | _logger = logger; |
| | | _httpContextAccessor = httpContextAccessor; |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 客户端连接服务端 |
| | | /// </summary> |
| | |
| | | _logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Connection Server!"); |
| | | return base.OnConnectedAsync(); |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 客户端断开连接 |
| | | /// </summary> |
| | |
| | | public override Task OnDisconnectedAsync(Exception exception) |
| | | { |
| | | var id = Context.ConnectionId; |
| | | // 删除用户ID |
| | | UserIdsStore.Ids.Remove(id); |
| | | // 使用线程安全方法移除连接 |
| | | UserIdsStore.RemoveUser(id); |
| | | _logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Close Connection Server!"); |
| | | return base.OnDisconnectedAsync(exception); |
| | | } |
| | | /** |
| | | * 测试 |
| | | * */ |
| | | |
| | | /// <summary> |
| | | /// 给所有客户端发送消息 |
| | | /// </summary> |
| | |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 添加到在线用户列表 |
| | | /// 添加到在线用户列表(线程安全版) |
| | | /// </summary> |
| | | /// <param name="usercode"></param> |
| | | /// <param name="usercode">用户编码</param> |
| | | /// <returns></returns> |
| | | public async Task AddUser(string usercode) |
| | | { |
| | | if (string.IsNullOrEmpty(usercode)) |
| | | { |
| | | _logger.LogWarning("AddUser方法接收的usercode为空,忽略操作"); |
| | | return; |
| | | } |
| | | |
| | | string cid = Context.ConnectionId; |
| | | if (!UserIdsStore.Ids.ContainsValue(usercode)) |
| | | try |
| | | { |
| | | await Task.Run(() => UserIdsStore.Ids.Add(cid, usercode)); |
| | | // 调用线程安全的添加/更新方法 |
| | | UserIdsStore.AddOrUpdateUser(cid, usercode); |
| | | _logger.LogInformation($"用户[{usercode}]的连接[{cid}]已注册到在线列表"); |
| | | } |
| | | else |
| | | catch (Exception ex) |
| | | { |
| | | //lambada表达式:根据值去键名Key |
| | | string key = UserIdsStore.Ids.FirstOrDefault(d => d.Value == usercode).Key.ToString(); |
| | | // 创建一个新的键值对 |
| | | UserIdsStore.Ids.Add(cid, usercode); |
| | | // 移除旧的键值对 |
| | | UserIdsStore.Ids.Remove(key); |
| | | _logger.LogError(ex, $"添加用户[{usercode}]连接[{cid}]失败"); |
| | | throw; // 抛出异常让客户端感知错误 |
| | | } |
| | | |
| | | await Task.CompletedTask; // 无异步操作时返回已完成任务 |
| | | } |
| | | } |
| | | } |