2018-12-25 17:08:43 +01:00
|
|
|
|
using System;
|
|
|
|
|
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>
|
|
|
|
|
public class Server
|
|
|
|
|
{
|
|
|
|
|
// ---- FIELDS -------------------------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
private readonly List<Client> _clients = new List<Client>();
|
|
|
|
|
|
|
|
|
|
// ---- 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();
|
|
|
|
|
Console.WriteLine($"Listening on port {port}...");
|
|
|
|
|
|
2018-12-25 17:36:36 +01:00
|
|
|
|
// Continually accept clients and dispatch them to their listening thread.
|
2018-12-25 17:08:43 +01:00
|
|
|
|
while (true)
|
|
|
|
|
{
|
|
|
|
|
Client client = new Client(tcpListener.AcceptTcpClient(), this);
|
|
|
|
|
_clients.Add(client);
|
|
|
|
|
|
2018-12-25 17:36:36 +01:00
|
|
|
|
Task.Run(client.Listen).ContinueWith(_ =>
|
2018-12-25 17:08:43 +01:00
|
|
|
|
{
|
|
|
|
|
_clients.Remove(client);
|
|
|
|
|
client.Dispose();
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|