消防培训系统服务器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.2 KiB

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AX.FireTrainingSys.Services
{
/// <summary>
/// 连接管理。
/// </summary>
public class ConnectionManager : IEnumerable<KeyValuePair<string, GroupCollection>>
{
private ConcurrentDictionary<string, GroupCollection> dict = new ConcurrentDictionary<string, GroupCollection>();
public int Count => dict.Count;
public bool IsEmpty => dict.IsEmpty;
/// <summary>
/// 加入房间。
/// </summary>
/// <param name="connectionId"></param>
/// <param name="group"></param>
/// <returns></returns>
public void AddToGroup(string connectionId, Group group)
{
if (group is null)
throw new ArgumentNullException(nameof(group));
var groupCollection = dict.GetOrAdd(connectionId, new GroupCollection());
groupCollection.Add(group);
}
/// <summary>
/// 离开房间。
/// </summary>
/// <param name="connectionId"></param>
/// <param name="groupName"></param>
/// <returns></returns>
public bool RemoveFromGroup(string connectionId, string groupName)
{
if (dict.TryGetValue(connectionId, out var groupCollection))
{
groupCollection.Remove(groupName);
if (groupCollection.IsEmpty())
{
dict.TryRemove(connectionId, out _);
return true;
}
}
return false;
}
public void Clear() => dict.Clear();
public bool Contains(string connId) => dict.ContainsKey(connId);
public GroupCollection GroupCollection(string connectionId)
{
dict.TryGetValue(connectionId, out var groupCollection);
return groupCollection;
}
public IEnumerator<KeyValuePair<string, GroupCollection>> GetEnumerator()
{
return dict.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}