using log4net; using Microsoft.AspNet.SignalR.Hubs; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Threading.Tasks; using VueWebCoreApi.Models; using VueWebCoreApi.Tools; namespace VueWebCoreApi.SignalR { public class ChatHub : Hub { private readonly IHttpContextAccessor _httpContextAccessor; private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(ChatHub)); ILogger _logger; public ChatHub(ILogger logger, IHttpContextAccessor httpContextAccessor) { _logger = logger; _httpContextAccessor = httpContextAccessor; } /// /// 客户端连接服务端 /// /// public override Task OnConnectedAsync() { log.Info("开启连接服务"); var id = Context.ConnectionId; _logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Connection Server!"); return base.OnConnectedAsync(); } /// /// 客户端断开连接 /// /// /// public override Task OnDisconnectedAsync(Exception exception) { var id = Context.ConnectionId; // 删除用户ID UserIdsStore.Ids.Remove(id); _logger.LogInformation($"Client ConnectionId=> [[{id}]] Already Close Connection Server!"); return base.OnDisconnectedAsync(exception); } /** * 测试 * */ /// /// 给所有客户端发送消息 /// /// public async Task SendMessage(string data) { await Clients.All.SendAll(data); } /// /// 添加到在线用户列表 /// /// /// public async Task AddUser(string usercode) { string cid = Context.ConnectionId; if (!UserIdsStore.Ids.ContainsValue(usercode)) { await Task.Run(() => UserIdsStore.Ids.Add(cid, usercode)); } else { //lambada表达式:根据值去键名Key string key = UserIdsStore.Ids.FirstOrDefault(d => d.Value == usercode).Key.ToString(); // 创建一个新的键值对 UserIdsStore.Ids.Add(cid, usercode); // 移除旧的键值对 UserIdsStore.Ids.Remove(key); } } } }