TigerEmu/Networking/Game/Sessions/GameSessionManager.cs

56 lines
1.5 KiB
C#

using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Net.WebSockets;
namespace Tiger.Networking.Game.Sessions;
public class GameSessionManager : IGameSessionManager
{
private readonly ConcurrentDictionary<string, GameSession> _sessions = new();
public GameSession AddSession(TcpClient client)
{
var sessionId = Guid.NewGuid().ToString();
var gameSession = new GameSession(client, sessionId);
_sessions.TryAdd(sessionId, gameSession);
return gameSession;
}
public void RemoveSession(TcpClient client)
{
var session = GetSession(client);
if (session != null)
{
_sessions.TryRemove(session.SessionId, out _);
}
}
public void CloseAll()
{
foreach (var session in _sessions.Values)
{
session.Client.Close();
}
}
public GameSession? GetSession(TcpClient client)
{
return (from session in _sessions where session.Value.Client == client select session.Value).FirstOrDefault();
}
public GameSession? GetSession(string sessionId)
{
return _sessions.TryGetValue(sessionId, out var gameSession) ? gameSession : null;
}
public async Task CloseAsync(GameSession session)
{
if (!_sessions.TryGetValue(session.SessionId, out var gameSession)) return;
if (gameSession.Client.Connected)
{
gameSession.Client.Close();
}
_sessions.TryRemove(session.SessionId, out _);
}
}