网站首页 网站源码
website
站点相关全部源代码,隐藏了一些关于服务器的信息
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();
            }
        }
    }
}
loading