Files
GameServer/MistoxServer/Interface/ServerInterface.cs
T
2026-07-03 11:37:41 -07:00

52 lines
2.3 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Mistox.Server;
namespace Mistox {
public class ServerInterface {
public static MistoxServer ServerInstance; // Server Data
public static ServerListener Listener; // Server Listener
public static ConcurrentDictionary<string, TcpClientConnection> Connections; // Server Connections
public event Action<TcpClientConnection> onUserConnected; // User connected event handler
public event Action<dynamic> onDataReceived; // Data received event handler
public event Action<TcpClientConnection> onUserDisconnected; // User disconnected event handler
public ServerInterface( int port, string serverName ) {
// Initilize the server
ServerInstance = new MistoxServer() {
ServerName = serverName,
BindAddress = IPAddress.Any,
Port = port,
MaxClients = 10
};
Connections = new ConcurrentDictionary<string, TcpClientConnection>();
// Setup the event handlers
ServerInstance.onUserConnected += (TcpClientConnection connectedUser) => { onUserConnected?.Invoke(connectedUser); };
ServerInstance.onDataReceived += (dynamic data) => { onDataReceived?.Invoke(data); };
ServerInstance.onUserDisconnected += (TcpClientConnection disconnectedUser) => { onUserDisconnected?.Invoke(disconnectedUser); };
// Start listening for connections and wire up the server
Listener = new ServerListener();
Console.WriteLine( "The Server is initilized and waiting for clients to connect at port : " + port );
}
public async Task SendAllClients<Packet>(Packet data) {
foreach( KeyValuePair<string, TcpClientConnection> cur in Connections ) {
await cur.Value.Connection.Send(data);
}
}
public async Task SendClient<Packet>(string UserName, Packet data) {
await Connections[UserName].Connection.Send( data );
}
}
}