using System; using System.Collections.Concurrent; using System.Net; using System.Threading.Tasks; using Mistox.ResevedPackets; namespace Mistox.Server { public class MistoxServer { // Class Definitions public string ServerName { get; private set; } = ""; // The name of the server public int MaxClients { get; set; } = 10; // The max players per server public float ConnectionRange { get; set; } = 40; // InGame distance for valid conections public string ConnectionKey { get; set; } = ""; // The connection key for the server public int ConnectionTimeoutSeconds { get; set; } = 10; // If no reply in time kill the connection public bool Alive { get; set; } = true; // Is the server running public ConcurrentDictionary Connections; // All the active connections. key is username private readonly ServerListener Listener; // The Connection Listener singleton public MistoxServer(IPEndPoint ListenerAddress, string serverName) { Listener = new ServerListener(ListenerAddress, this); Connections = new ConcurrentDictionary(); ServerName = serverName; Console.WriteLine( "The Server is initilized and waiting for clients to connect at port : " + ListenerAddress.Port ); } async Task ProcessAuthRequest(UserAuthPacket packet) { // Need to set the connection userName via this packet string user = packet.UserName; packet.ServerName = ServerName; packet.AuthSuccessful = packet.ConnectionKey == ConnectionKey ? 1 : 0; await SendClient(packet.UserName, packet); } // Functions public event Action onUserConnected; public void InvokeUserConnected( ServerConnection user ){ onUserConnected?.Invoke( user ); } public event Action onDataReceived; public void InvokeDataReceived( dynamic data ){ switch (data as object) { case UserAuthPacket packet: Task.Run(async () => { try { await ProcessAuthRequest(packet); } catch {} }); break; case null: Console.WriteLine("Received a null packet."); break; default: onDataReceived?.Invoke(data); break; } } public event Action onUserDisconnected; public void InvokeUserDisconnected( ServerConnection user ){ onUserDisconnected?.Invoke( user ); } public async Task SendAllClients(Packet data) { foreach( ServerConnection cur in Connections.Values ) { await cur.Send(data); } } public async Task SendClient(string UserName, Packet data) { await Connections[UserName].Send( data ); } } }