namespace ZhiYi.Core.Application.Services.Implements { /// /// 客户端连接管理 /// public class ConnectionClientManagerService : IConnectionClientManagerService { private readonly ConcurrentDictionary dic = new(); private readonly IDatabase _redis; public ConnectionClientManagerService( IConnectionMultiplexer connectionMultiplexer ) { _redis = connectionMultiplexer.GetDatabase(); } /// /// 添加客户端 /// /// 客户端ID /// /// public Task AddAsync(string clientId, IWebSocket webSocket) { if (!clientId.IsNullOrEmpty()) { _redis.StringSet($"client", clientId); dic.AddOrUpdate(clientId, webSocket); } return Task.CompletedTask; } /// /// 指定客户端发送消息 /// /// 客户端ID /// 消息内容 /// public async Task SendAsync(string clientId, string message) { if (dic.TryGetValue(clientId, out var webSocket)) { await webSocket.SendAsync(message); return true; } return false; } /// /// 广播消息 /// /// /// public async Task SendAllAsync(string message) { if (dic.Count > 0) { foreach (var d in dic) { await d.Value.SendAsync(message); } return true; } return false; } /// /// 移除客户端并释放资源 /// /// 客户端ID /// public Task RemoveAsync(string clientId) { if(dic.TryRemove(clientId,out var webSocket)) { webSocket.SafeDispose(); } return Task.CompletedTask; } } }