using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; namespace Syroot.Worms.OnlineWorms.Server { /// /// Represents a server listening for incoming client connections and dispatching them into /// instances. /// public class Server { // ---- FIELDS ------------------------------------------------------------------------------------------------- private readonly List _clients = new List(); // ---- METHODS (INTERNAL) ------------------------------------------------------------------------------------- /// /// Starts the server by accepting new client connections under the given and /// dispatching them into asynchronous handling threads. This call is blocking. /// /// The port on which to listen for new client connections. internal void Listen(int port) { TcpListener tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); Console.WriteLine($"Listening on port {port}..."); // Continually accept clients and dispatch them to their listening thread. while (true) { Client client = new Client(tcpListener.AcceptTcpClient(), this); _clients.Add(client); Task.Run(client.Listen).ContinueWith(_ => { _clients.Remove(client); client.Dispose(); }); } } } }