Files
GameServer/MistoxServer/Client/MistoxClient.cs
T

106 lines
3.8 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using Mistox.ResevedPackets;
namespace Mistox.Client {
public class MistoxClient {
public string ServerName { get; set; } = ""; // The Name of the server
public bool Alive { get; set; } = true; // Is the server running
public mTCPClient ServerConnection;
public UdpClient ClientSocket;
public UDPReceiver UdpReceiver;
public ConcurrentDictionary<UInt128, mUDPClient> clientConnections; // IP Address, Client
public MistoxClient(IPEndPoint Server) {
// Create and listen on UDP
ClientSocket = new UdpClient( Server.Port );
UdpReceiver = new UDPReceiver( this );
// Create and connect to server on TCP
Console.WriteLine( "The client is initilized and trying to connect to the server at ip : " + Server.Address );
try {
ServerConnection = new mTCPClient( this, Server );
Console.WriteLine( "Connected to the server sucessfully" );
} catch( Exception e ) {
Console.WriteLine( "An error has occured with the connection to the server. Error { " );
Console.WriteLine( e.ToString() );
Console.WriteLine( "}" );
}
Alive = true;
}
/////////////////////////////
// Receive Methods
/////////////////////////////
public void UserConnected(UserConnectedPacket packet) {
mUDPClient user = new mUDPClient(this, packet.ClientIPAddress, packet.ClientPort) {
UserName = packet.UserName
};
clientConnections[user.GetConnectionKey()] = user;
InvokeOnUserConnected(user);
}
public void UserDisconnected(UserDisconnectedPacket packet) {
mUDPClient client;
bool found = clientConnections.TryGetValue(packet.ConnectionKey, out client);
if (found) {
InvokeOnUserDisconnected( client );
client.Alive = false;
client.Dispose();
clientConnections[packet.ConnectionKey] = null;
}
}
/////////////////////////////
// Events
/////////////////////////////
public event Action<dynamic> onDataReceived;
public void InvokeOnReceived(dynamic DataPacket, IPEndPoint remote = null){
switch (DataPacket as object) {
case UserConnectedPacket packet:
UserConnected(packet);
break;
case UserDisconnectedPacket packet:
UserDisconnected(packet);
break;
case null:
Console.WriteLine("Received a null packet.");
break;
default:
onDataReceived?.Invoke(DataPacket);
break;
}
}
public event Action onServerConnected;
public void InvokeOnServerConnected(){
Alive = true;
onServerConnected?.Invoke();
}
public event Action<mUDPClient> onUserConnected;
public void InvokeOnUserConnected(mUDPClient ConnectedUser){
onUserConnected?.Invoke(ConnectedUser);
}
public event Action<mUDPClient> onUserDisconnected;
public void InvokeOnUserDisconnected(mUDPClient DisconnectedUser){
onUserDisconnected?.Invoke(DisconnectedUser);
}
public event Action onServerDisconnected;
public void InvokeOnServerDisconnected(){
Alive = false;
onServerDisconnected?.Invoke();
}
}
}