using System.Collections.Concurrent; using NetCore; using NetCore.Protocol.MemoryPack; namespace NetServer.InternalServer; public class ServerLinkMnager { private Random _random = new Random(1); public static ServerLinkMnager Instance { get { if (_serverLinkMnager == null) { _serverLinkMnager = new ServerLinkMnager(); } return _serverLinkMnager; } } public static ServerLinkMnager _serverLinkMnager; public class ServerInfo { public long serverId; public IConnection ServerConnection; } public ConcurrentDictionary> InternalLogicManagerDic = new ConcurrentDictionary>(); public void AddServerConnection(ServerType serverType, IConnection iConnection) { lock (InternalLogicManagerDic) { if (InternalLogicManagerDic.TryGetValue((int)serverType, out var serverDic)) { if (serverDic.TryGetValue( iConnection.ConnectionId, out var serverInfo)) { Console.Error.WriteLine("重复添加了服务器"); } else { serverDic.TryAdd( iConnection.ConnectionId, new ServerInfo() { serverId = iConnection.ConnectionId, ServerConnection = iConnection }); } } else { serverDic = new ConcurrentDictionary(); serverDic.TryAdd( iConnection.ConnectionId, new ServerInfo() { serverId = iConnection.ConnectionId, ServerConnection = iConnection }); InternalLogicManagerDic.TryAdd((int)serverType, serverDic); } } } public void RemoveServerConnection(ServerType serverType, long serverId) { lock (InternalLogicManagerDic) { if (InternalLogicManagerDic.TryGetValue((int)serverType, out var serverDic)) { if (serverDic.TryGetValue(serverId, out var serverInfo)) { serverDic.TryRemove(serverId, out _); } } } } public IConnection GetServerConnection(ServerType serverType, long serverId) { if (InternalLogicManagerDic.TryGetValue((int)serverType, out var serverDic)) { if (serverDic.TryGetValue(serverId, out var serverInfo)) { return serverInfo.ServerConnection; } } return null; } public IConnection GetServerConnection(ServerType serverType) { if (InternalLogicManagerDic.TryGetValue((int)serverType, out var serverDic)) { int maxCount = serverDic.Count; int index = _random.Next(0, maxCount); int corrIndex = 0; foreach (var VARIABLE in serverDic.Values) { if (index == corrIndex) { return VARIABLE.ServerConnection; } corrIndex++; } } return null; } }