2023-10-08 14:12:01 +00:00
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
using System.Net;
|
2023-10-14 17:39:26 +00:00
|
|
|
|
using AscNet.Logging;
|
2023-10-08 14:12:01 +00:00
|
|
|
|
|
|
|
|
|
namespace AscNet.GameServer
|
|
|
|
|
{
|
|
|
|
|
public class Server
|
|
|
|
|
{
|
2023-10-14 17:39:26 +00:00
|
|
|
|
public static Logger log;
|
2023-10-08 14:12:01 +00:00
|
|
|
|
public readonly Dictionary<string, Session> Sessions = new();
|
|
|
|
|
private static Server? _instance;
|
|
|
|
|
private readonly TcpListener listener;
|
|
|
|
|
|
|
|
|
|
public static Server Instance
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
return _instance ??= new Server();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-11-13 12:10:02 +00:00
|
|
|
|
static Server()
|
2023-10-08 14:12:01 +00:00
|
|
|
|
{
|
2023-10-14 17:39:26 +00:00
|
|
|
|
// TODO: add loglevel based on appsettings
|
|
|
|
|
LogLevel logLevel = LogLevel.DEBUG;
|
|
|
|
|
LogLevel fileLogLevel = LogLevel.DEBUG;
|
|
|
|
|
log = new(typeof(Server), logLevel, fileLogLevel);
|
2023-11-13 12:10:02 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Server()
|
|
|
|
|
{
|
2023-10-08 14:12:01 +00:00
|
|
|
|
listener = new(IPAddress.Parse("0.0.0.0"), Common.Common.config.GameServer.Port);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Start()
|
|
|
|
|
{
|
2023-10-11 17:39:04 +00:00
|
|
|
|
while (true)
|
2023-10-08 14:12:01 +00:00
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
listener.Start();
|
2023-10-14 17:39:26 +00:00
|
|
|
|
log.Info($"{nameof(GameServer)} started and listening on port {Common.Common.config.GameServer.Port}");
|
2023-10-08 14:12:01 +00:00
|
|
|
|
|
2023-10-11 17:39:04 +00:00
|
|
|
|
while (true)
|
2023-10-08 14:12:01 +00:00
|
|
|
|
{
|
|
|
|
|
TcpClient tcpClient = listener.AcceptTcpClient();
|
|
|
|
|
string id = tcpClient.Client.RemoteEndPoint!.ToString()!;
|
|
|
|
|
|
2023-10-14 17:39:26 +00:00
|
|
|
|
log.Warn($"{id} connected");
|
2023-10-08 14:12:01 +00:00
|
|
|
|
Sessions.Add(id, new Session(id, tcpClient));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2023-10-14 17:39:26 +00:00
|
|
|
|
log.Error("TCP listener error: " + ex.Message);
|
|
|
|
|
log.Info("Waiting 3 seconds before restarting...");
|
2023-10-08 14:12:01 +00:00
|
|
|
|
Thread.Sleep(3000);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-11-13 12:10:02 +00:00
|
|
|
|
|
|
|
|
|
public Session? SessionFromUID(long uid)
|
|
|
|
|
{
|
2023-11-14 14:12:15 +00:00
|
|
|
|
return Sessions.Select(x => x.Value).FirstOrDefault(x => x.player.PlayerData.Id == uid);
|
2023-11-13 12:10:02 +00:00
|
|
|
|
}
|
2023-10-08 14:12:01 +00:00
|
|
|
|
}
|
|
|
|
|
}
|