using System.Collections.Generic;
using System.Linq;
using Dpz.Core.Public.ViewModel;
namespace Dpz.Core.Web.Library
{
public class ChatCurrentConnections
{
/// <summary>
/// 在线用户
/// </summary>
private static readonly Dictionary<string, VmUserInfo> ConnectionUsers = new Dictionary<string, VmUserInfo>();
private static readonly object LockObj = new object();
private static ChatCurrentConnections _instance;
private ChatCurrentConnections() { }
public static ChatCurrentConnections GetInstance()
{
if (_instance != null) return _instance;
lock (LockObj)
{
_instance = new ChatCurrentConnections();
return _instance;
}
}
public VmUserInfo this[string index] => ConnectionUsers[index];
public void Add(string connectionId, VmUserInfo user)
{
lock (LockObj)
{
if (ConnectionUsers.ContainsKey(connectionId))
{
ConnectionUsers.Add(connectionId, user);
}
else
{
ConnectionUsers[connectionId] = user;
}
}
}
public VmUserInfo Get(string connectionId)
{
if (!ConnectionUsers.ContainsKey(connectionId)) return null;
return ConnectionUsers[connectionId];
}
public void Remove(string connectionId)
{
if (ConnectionUsers.ContainsKey(connectionId))
{
//ConnectionUsers.Values.Any(x => x.Id == this[connectionId].Id)
lock (LockObj)
{
ConnectionUsers.Remove(connectionId);
}
}
}
public List<VmUserInfo> GetAllOnlineUsers()
{
lock (LockObj)
{
return ConnectionUsers.Select(x => x.Value).ToList();
}
}
}
}