43 lines
1.8 KiB
C#
43 lines
1.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net;
|
|
using System.Threading.Tasks;
|
|
using Mistox.Server;
|
|
|
|
namespace Mistox {
|
|
public class ServerInterface {
|
|
|
|
public static ServerEntity ServerInstance; // Server Data
|
|
|
|
public event Action<ServerConnection> onUserConnected; // User connected event handler
|
|
public event Action<dynamic> onDataReceived; // Data received event handler
|
|
public event Action<ServerConnection> onUserDisconnected; // User disconnected event handler
|
|
|
|
public ServerInterface( int port, string serverName ) {
|
|
|
|
IPEndPoint listenerAddress = new IPEndPoint( IPAddress.Any, port );
|
|
|
|
// Initilize the server
|
|
ServerInstance = new ServerEntity(listenerAddress);
|
|
ServerInstance.ServerName = serverName;
|
|
|
|
// Setup the event handlers
|
|
ServerInstance.onUserConnected += (ServerConnection connectedUser) => { onUserConnected?.Invoke(connectedUser); };
|
|
ServerInstance.onDataReceived += (dynamic data) => { onDataReceived?.Invoke(data); };
|
|
ServerInstance.onUserDisconnected += (ServerConnection disconnectedUser) => { onUserDisconnected?.Invoke(disconnectedUser); };
|
|
|
|
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, ServerConnection> cur in ServerInstance.Connections ) {
|
|
await cur.Value.Send(data);
|
|
}
|
|
}
|
|
|
|
public async Task SendClient<Packet>(string UserName, Packet data) {
|
|
await ServerInstance.Connections[UserName].Send( data );
|
|
}
|
|
}
|
|
}
|