1
0
mirror of https://gitlab.com/Syroot/Worms.git synced 2025-01-23 12:17:58 +03:00
2019-01-01 22:03:10 +01:00

58 lines
2.3 KiB
C#

using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Syroot.Worms.OnlineWorms.Server
{
/// <summary>
/// Represents a server listening for incoming client connections and dispatching them into <see cref="Client"/>
/// instances.
/// </summary>
internal class Server
{
// ---- FIELDS -------------------------------------------------------------------------------------------------
private readonly List<Client> _clients = new List<Client>();
// ---- PROPERTIES ---------------------------------------------------------------------------------------------
internal string Name => "Online Worms Private Server";
internal string RegionName => "Global";
internal ushort Version => 114;
internal Log Log { get; } = new Log();
// ---- METHODS (INTERNAL) -------------------------------------------------------------------------------------
/// <summary>
/// Starts the server by accepting new client connections under the given <paramref name="port"/> and
/// dispatching them into asynchronous handling threads. This call is blocking.
/// </summary>
/// <param name="port">The port on which to listen for new client connections.</param>
internal void Listen(int port)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
Log.Write(LogCategory.Server, $"Listening on port {port}...");
while (true)
{
// Continually accept clients.
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Log.Write(LogCategory.Connect, $"{tcpClient.Client.RemoteEndPoint} connected");
Client client = new Client(tcpClient, this);
_clients.Add(client);
// Dispatch the client into its listening thread and remove it when listening aborts.
Task.Run(client.Listen).ContinueWith(_ =>
{
Log.Write(LogCategory.Disconnect, $"{client.TcpClient.Client.RemoteEndPoint} disconnected");
_clients.Remove(client);
client.Dispose();
});
}
}
}
}