TigerEmu/Networking/Game/Sessions/GameSessionManager.cs

56 lines
1.5 KiB
C#
Raw Normal View History

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