58 lines
2.3 KiB
C#
Raw Normal View History

2018-12-25 22:12:37 +01:00
using System.Collections.Generic;
2018-12-25 17:08:43 +01:00
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>
2018-12-25 22:12:37 +01:00
internal class Server
2018-12-25 17:08:43 +01:00
{
// ---- FIELDS -------------------------------------------------------------------------------------------------
private readonly List<Client> _clients = new List<Client>();
2018-12-25 22:12:37 +01:00
// ---- PROPERTIES ---------------------------------------------------------------------------------------------
internal string Name => "Online Worms Private Server";
internal string RegionName => "Global";
internal ushort Version => 114;
internal Log Log { get; } = new Log();
2018-12-25 17:08:43 +01:00
// ---- 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();
2018-12-25 22:12:37 +01:00
Log.Write(LogCategory.Server, $"Listening on port {port}...");
2018-12-25 17:08:43 +01:00
while (true)
{
2018-12-25 22:12:37 +01:00
// Continually accept clients.
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Log.Write(LogCategory.Connect, $"{tcpClient.Client.RemoteEndPoint} connected");
Client client = new Client(tcpClient, this);
2018-12-25 17:08:43 +01:00
_clients.Add(client);
2018-12-25 22:12:37 +01:00
// Dispatch the client into its listening thread and remove it when listening aborts.
2018-12-25 17:36:36 +01:00
Task.Run(client.Listen).ContinueWith(_ =>
2018-12-25 17:08:43 +01:00
{
2018-12-25 22:12:37 +01:00
Log.Write(LogCategory.Disconnect, $"{client.TcpClient.Client.RemoteEndPoint} disconnected");
2018-12-25 17:08:43 +01:00
_clients.Remove(client);
client.Dispose();
});
}
}
}
}