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

68 lines
2.8 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 Action onServerConnected;
public event Action<UDPEndpoint> onUserConnected;
public event Action<dynamic> onDataReceived;
public event Action<UDPEndpoint> onUserDisconnected;
public event Action onServerDisconnected;
public ClientInterface( string IpOrHostName, int Port ) {
// Wire up the Mistox server client
ServerClientInstance = new MistoxServerClient() {
Port = Port
};
ServerClientInstance.onServerConnected += onServerConnected;
ServerClientInstance.onUserConnected += (UDPEndpoint endpoint) => { onUserConnected?.Invoke(endpoint); };
ServerClientInstance.onDataReceived += (dynamic data) => { onDataReceived?.Invoke(data); };
ServerClientInstance.onUserDisconnected += (UDPEndpoint endpoint) => { onUserDisconnected?.Invoke(endpoint); };
ServerClientInstance.onServerDisconnected += onServerDisconnected;
// 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 );
} 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 );
}
}
public async Task SendClient<Packet>(string UserName, Packet data) {
await clientConnections[UserName].Connection.Send( data );
}
public async Task SendServer<Packet>(Packet data) {
await serverConnection.Send( data );
}
}
}