Files
GameServer/MistoxServer/Interface/ClientInterface.cs
T
2026-07-02 21:48:43 -07:00

63 lines
2.5 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Mistox.Client;
namespace Mistox {
public class ClientInterface {
public static MistoxServerClient ServerClientInstance;
public static mTCPClient serverConnection;
public static ConcurrentDictionary<string, UDPEndpoint> clientConnections;
public event EventHandler onUserConnected;
public event EventHandler onReceive;
public event EventHandler onUserDisconnected;
public ClientInterface( string IpOrHostName, int Port ) {
ServerClientInstance = new MistoxServerClient() {
Port = Port
};
// Get Server IP
IPHostEntry host = Dns.GetHostEntry( IpOrHostName );
IPEndPoint ServerDenstination = new IPEndPoint(0, 0);
foreach( IPAddress entry in host.AddressList ) {
if ( entry.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ) {
ServerDenstination = new IPEndPoint( entry, Port );
}
}
Console.WriteLine( "The client is initilized and trying to connect to the server at ip : " + ServerDenstination.Address );
// Make a TCP connection to the server
try {
serverConnection = new mTCPClient( ServerDenstination );
serverConnection.on +=
serverConnection.onReceive += ( object o, EventArgs e ) => { onReceive?.Invoke( o, e ); };
serverConnection.onDisconnected += ( object o, EventArgs e ) => { onUserDisconnected?.Invoke( o, e ); };
} catch( Exception e ) {
Console.WriteLine( "An error has occured with the connection to the server. Error { " );
Console.WriteLine( e.ToString() );
Console.WriteLine( "}" );
}
}
public async Task SendAllClients<Packet>(Packet data) {
foreach(KeyValuePair<string, UDPEndpoint> cur in clientConnections){
await cur.Value.Connection.Send( data, cur.Value.Destination );
}
}
public async Task SendClient<Packet>(string UserName, Packet data) {
await clientConnections[UserName].Connection.Send( data, clientConnections[UserName].Destination );
}
public async Task SendServer<Packet>(Packet data) {
await serverConnection.Send( data );
}
}
}