using System.Collections.Concurrent; using DotNetty.Buffers; using DotNetty.Transport.Channels; using log4net; namespace HybirdFrameworkDriver.Session; public class SessionMgr { private static readonly ILog Log = LogManager.GetLogger(typeof(SessionMgr)); private static readonly ConcurrentDictionary Dictionary = new ConcurrentDictionary(); private static readonly ConcurrentDictionary ModbusDictionary = new ConcurrentDictionary(); public ConcurrentDictionary? BusinessMap { get; set; } public static IoSession? GetSession(string key) { if (Dictionary.ContainsKey(key)) { IoSession? value; Dictionary.TryGetValue(key, out value); return value; } return null; } public static List GetSessionList() { return Dictionary.Values.ToList(); } public static ModbusSession GetModbusSession(string key) { if (ModbusDictionary.ContainsKey(key)) { ModbusSession value; ModbusDictionary.TryGetValue(key, out value); return value; } return null; } public static void RegisterSession(IChannel channel, IoSession ioSession) { var oldKey = ioSession.Key; if (oldKey != null) { IoSession? session; Dictionary.Remove(oldKey, out session); } ChannelUtils.AddChannelSession(channel, ioSession); ioSession.Key = channel.Id.ToString(); Dictionary.AddOrUpdate(channel.Id.ToString(), ioSession, (k, oldSession) => ioSession); } public static void RegisterModbusSession(string key, ModbusSession ioSession) { var oldKey = ioSession.Key; if (oldKey != null) { ModbusSession? session; ModbusDictionary.Remove(oldKey, out session); } ioSession.Key = key; ModbusDictionary.AddOrUpdate(key, ioSession, (k, oldSession) => ioSession); } public static void UnregisterSession(IChannel channel) { IoSession session = ChannelUtils.GetSessionBy(channel); IoSession? outSession; Dictionary.Remove(session.Key, out outSession); session.Close(); } public static void Broadcast(IByteBuffer buffer, ConcurrentDictionary dictionary) { foreach (IoSession session in dictionary.Values) { session.Send(buffer); } } public static Object GetAttr(IoSession session, String key) { Object? obj; session.BusinessMap.TryGetValue(key, out obj); return obj; } public static void SetAttr(IoSession session, String key, Object obj) { session.BusinessMap.TryAdd(key, obj); } public static Object GetAttrByKey(String? key, String mapKey) { if (!string.IsNullOrEmpty(key)) { Dictionary.TryGetValue(key, out IoSession? session); if (session != null) { session.BusinessMap.TryGetValue(mapKey, out Object? obj); if (obj != null) { return (int)obj; } } } return 0; } public static void SetAttrModbus(ModbusSession session, String key, Object obj) { if (session.BusinessMap == null) { session.BusinessMap = new ConcurrentDictionary(); } session.BusinessMap.TryAdd(key, obj); } public static Object GetAttrModbus(String key, String mapKey) { ModbusDictionary.TryGetValue(key, out ModbusSession? session); if (session != null) { session.BusinessMap.TryGetValue(mapKey, out Object? obj); if (obj != null) { return (int)obj; } } return 0; } }