78 lines
2.1 KiB
C#
78 lines
2.1 KiB
C#
using System.Collections.Concurrent;
|
|
|
|
namespace ZhiYi.Core.Application.Services.Implements
|
|
{
|
|
/// <summary>
|
|
/// 客户端连接管理
|
|
/// </summary>
|
|
public class ConnectionClientManagerService : IConnectionClientManagerService
|
|
{
|
|
private ConcurrentDictionary<string, IWebSocket> dic = new();
|
|
|
|
|
|
/// <summary>
|
|
/// 添加客户端
|
|
/// </summary>
|
|
/// <param name="clientId">客户端ID</param>
|
|
/// <param name="webSocket"></param>
|
|
/// <returns></returns>
|
|
public Task AddAsync(string clientId, IWebSocket webSocket)
|
|
{
|
|
if (!clientId.IsNullOrEmpty())
|
|
{
|
|
dic.AddOrUpdate(clientId, webSocket);
|
|
}
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 指定客户端发送消息
|
|
/// </summary>
|
|
/// <param name="clientId">客户端ID</param>
|
|
/// <param name="message">消息内容</param>
|
|
/// <returns></returns>
|
|
public async Task<bool> SendAsync(string clientId, string message)
|
|
{
|
|
if (dic.TryGetValue(clientId, out var webSocket))
|
|
{
|
|
await webSocket.SendAsync(message);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 广播消息
|
|
/// </summary>
|
|
/// <param name="message"></param>
|
|
/// <returns></returns>
|
|
public async Task<bool> SendAllAsync(string message)
|
|
{
|
|
if (dic.Count > 0)
|
|
{
|
|
foreach (var d in dic)
|
|
{
|
|
await d.Value.SendAsync(message);
|
|
}
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 移除客户端并释放资源
|
|
/// </summary>
|
|
/// <param name="clientId">客户端ID</param>
|
|
/// <returns></returns>
|
|
public Task RemoveAsync(string clientId)
|
|
{
|
|
if(dic.TryRemove(clientId,out var webSocket))
|
|
{
|
|
webSocket.SafeDispose();
|
|
}
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|