Wire up the event handlers

This commit is contained in:
derek committed 2026-07-03 11:37:41 -07:00
1 parent a04516c470
commit a689f2656f
11 files changed
+90 -76

No files matched your search

@@ -3,21 +3,37 @@
namespace Mistox.Client { namespace Mistox.Client {
public class MistoxServerClient { public class MistoxServerClient {
public string ServerName { get; set; } = ""; // The Name of the server public string ServerName { get; set; } = ""; // The Name of the server
public bool Alive { get; set; } = true; // Is the server running public bool Alive { get; set; } = true; // Is the server running
public int Port { get; set; } = 9126; // What Port to bind on public int Port { get; set; } = 9126; // What Port to bind on
public event EventHandler onUserConnected;
public event Action onServerConnected;
public void InvokeOnServerConnected(){
Alive = true;
onServerConnected?.Invoke();
}
public event Action<UDPEndpoint> onUserConnected;
public void InvokeOnUserConnected(UDPEndpoint ConnectedUser){ public void InvokeOnUserConnected(UDPEndpoint ConnectedUser){
onUserConnected?.Invoke(ConnectedUser, new EventArgs()); onUserConnected?.Invoke(ConnectedUser);
} }
public event EventHandler onReceived;
public event Action<dynamic> onDataReceived;
public void InvokeOnReceived(dynamic DataPacket){ public void InvokeOnReceived(dynamic DataPacket){
onReceived?.Invoke(DataPacket, new EventArgs()); onDataReceived?.Invoke(DataPacket);
} }
public event EventHandler onUserDisconnected;
public event Action<UDPEndpoint> onUserDisconnected;
public void InvokeOnUserDisconnected(UDPEndpoint DisconnectedUser){ public void InvokeOnUserDisconnected(UDPEndpoint DisconnectedUser){
onUserDisconnected?.Invoke(DisconnectedUser, new EventArgs()); onUserDisconnected?.Invoke(DisconnectedUser);
}
public event Action onServerDisconnected;
public void InvokeOnServerDisconnected(){
Alive = false;
onServerDisconnected?.Invoke();
} }
} }
@@ -4,7 +4,6 @@ namespace Mistox.Client {
public class UDPEndpoint { public class UDPEndpoint {
public string UserName { get; set; } = ""; // The Players UserName public string UserName { get; set; } = ""; // The Players UserName
public bool Alive { get; set; } = true; // Is the connection alive public bool Alive { get; set; } = true; // Is the connection alive
public IPEndPoint Destination { get; set; } // The IP destination for the connection
public mUDPClient Connection { get; set; } // The UDP Client Object public mUDPClient Connection { get; set; } // The UDP Client Object
} }
} }
@@ -0,0 +1,8 @@
using Mistox.Attributes;
[mPacket(0xFF)]
public class UserConnectionPacket {
string UserName { get; set; }
long RemoteIP { get; set; }
int Port { get; set; }
}
+6 -16
View File
@@ -15,7 +15,7 @@ namespace Mistox.Client {
Server = new TcpClient( AddressFamily.InterNetwork ); Server = new TcpClient( AddressFamily.InterNetwork );
Server.NoDelay = true; Server.NoDelay = true;
Server.Connect( ServerAddress ); Server.Connect( ServerAddress );
ClientInterface.ServerClientInstance.Alive = true; ClientInterface.ServerClientInstance.InvokeOnServerConnected();
Thread RThread = new Thread(async () => { await ReceiveThread(); }); Thread RThread = new Thread(async () => { await ReceiveThread(); });
RThread.Start(); RThread.Start();
} }
@@ -24,27 +24,17 @@ namespace Mistox.Client {
using( NetworkStream ns = Server.GetStream() ) { using( NetworkStream ns = Server.GetStream() ) {
try { try {
while( ClientInterface.ServerClientInstance.Alive ) { while( ClientInterface.ServerClientInstance.Alive ) {
if( Server.Connected ) {
Console.WriteLine( "Connected to server" );
ClientInterface.ServerClientInstance.onConnected.Invoke( new object(), new EventArgs() );
} else if( !Server.Connected ) {
Console.WriteLine( "Disconnected from server" );
ClientInterface.ServerClientInstance.onDisconnected?.Invoke( new object(), new EventArgs() );
ClientInterface.ServerClientInstance.Alive = false;
}
byte[] StreamData = new byte[1024]; byte[] StreamData = new byte[1024];
int bytesRead = await ns.ReadAsync(StreamData, 0, StreamData.Length); int bytesRead = await ns.ReadAsync(StreamData, 0, StreamData.Length);
if( bytesRead > 0 ) { if( bytesRead > 0 ) {
dynamic data = mSerialize.tReceive( StreamData.Sub( 0, bytesRead ) ); dynamic data = Serializer.tReceive( StreamData.Sub( 0, bytesRead ) );
if( data != null ) { if( data != null ) {
ClientInterface.ServerClientInstance.onReceive?.Invoke( data, new EventArgs() ); ClientInterface.ServerClientInstance.InvokeOnReceived( data );
} }
} }
} }
} catch( Exception ) { } catch( Exception e ) {
Console.WriteLine( "You have disconnected from the server" ); Console.WriteLine( "TCP Receive exception : " + e.Message );
ClientInterface.ServerClientInstance.onDisconnected?.Invoke( new object(), new EventArgs() );
ClientInterface.ServerClientInstance.Alive = false;
} }
} }
} }
@@ -55,7 +45,7 @@ namespace Mistox.Client {
} }
public void Dispose() { public void Dispose() {
ClientInterface.ServerClientInstance.Alive = false; ClientInterface.ServerClientInstance.InvokeOnServerDisconnected();
Server.Close(); Server.Close();
Server = null; Server = null;
} }
+14 -12
View File
@@ -11,39 +11,41 @@ namespace Mistox.Client {
Socket udpClient; Socket udpClient;
public mUDPClient( IPEndPoint ServerAddress, string ConnectionID ) { IPEndPoint remoteHost;
public mUDPClient( long RemoteIP, int Port ) {
remoteHost = new IPEndPoint( RemoteIP, Port );
udpClient = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); udpClient = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp );
udpClient.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true ); udpClient.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true );
udpClient.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, 128 ); udpClient.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, 128 );
udpClient.Bind( new IPEndPoint( IPAddress.Any, ServerAddress.Port ) ); udpClient.Bind( new IPEndPoint( IPAddress.Any, Port ) );
Alive = true; ClientInterface.ServerClientInstance.Alive = true;
Port = ServerAddress.Port;
Thread Client = new Thread(async() => { await ReceiveThread(); }); Thread Client = new Thread(async() => { await ReceiveThread(); });
Client.Start(); Client.Start();
} }
async Task ReceiveThread() { async Task ReceiveThread() {
while( Alive ) { while( ClientInterface.ServerClientInstance.Alive ) {
try { try {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int bytesRead = await udpClient.ReceiveAsync( buffer ); int bytesRead = await udpClient.ReceiveAsync( buffer );
dynamic data = mSerialize.uReceive( buffer.Sub(0, bytesRead) ); dynamic data = Serializer.uReceive( buffer.Sub(0, bytesRead) );
if( data != null ) { if( data != null ) {
onReceived?.Invoke( data, new EventArgs() ); ClientInterface.ServerClientInstance.InvokeOnReceived( data );
} }
} catch( Exception ) { } catch( Exception e ) {
Console.WriteLine( "UDP Receive exception : " + e.Message );
} }
} }
} }
public async Task Send<T>( T Data, IPEndPoint remoteHost ) { public async Task Send<T>( T Data ) {
byte[] byteData = DataPacket.Serialize( Data ); byte[] byteData = DataPacket.Serialize( Data );
await udpClient.SendToAsync( byteData, SocketFlags.None, new IPEndPoint( remoteHost.Address, Port ) ); await udpClient.SendToAsync( byteData, SocketFlags.None, remoteHost );
} }
public void Dispose() { public void Dispose() {
Alive = false; ClientInterface.ServerClientInstance.Alive = false;
udpClient.Close(); udpClient.Close();
udpClient = null; udpClient = null;
} }
+13 -8
View File
@@ -12,15 +12,23 @@ namespace Mistox {
public static mTCPClient serverConnection; public static mTCPClient serverConnection;
public static ConcurrentDictionary<string, UDPEndpoint> clientConnections; public static ConcurrentDictionary<string, UDPEndpoint> clientConnections;
public event EventHandler onUserConnected; public event Action onServerConnected;
public event EventHandler onReceive; public event Action<UDPEndpoint> onUserConnected;
public event EventHandler onUserDisconnected; public event Action<dynamic> onDataReceived;
public event Action<UDPEndpoint> onUserDisconnected;
public event Action onServerDisconnected;
public ClientInterface( string IpOrHostName, int Port ) { public ClientInterface( string IpOrHostName, int Port ) {
// Wire up the Mistox server client
ServerClientInstance = new MistoxServerClient() { ServerClientInstance = new MistoxServerClient() {
Port = Port 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 // Get Server IP
IPHostEntry host = Dns.GetHostEntry( IpOrHostName ); IPHostEntry host = Dns.GetHostEntry( IpOrHostName );
@@ -35,9 +43,6 @@ namespace Mistox {
// Make a TCP connection to the server // Make a TCP connection to the server
try { try {
serverConnection = new mTCPClient( ServerDenstination ); 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 ) { } catch( Exception e ) {
Console.WriteLine( "An error has occured with the connection to the server. Error { " ); Console.WriteLine( "An error has occured with the connection to the server. Error { " );
Console.WriteLine( e.ToString() ); Console.WriteLine( e.ToString() );
@@ -47,12 +52,12 @@ namespace Mistox {
public async Task SendAllClients<Packet>(Packet data) { public async Task SendAllClients<Packet>(Packet data) {
foreach(KeyValuePair<string, UDPEndpoint> cur in clientConnections){ foreach(KeyValuePair<string, UDPEndpoint> cur in clientConnections){
await cur.Value.Connection.Send( data, cur.Value.Destination ); await cur.Value.Connection.Send( data );
} }
} }
public async Task SendClient<Packet>(string UserName, Packet data) { public async Task SendClient<Packet>(string UserName, Packet data) {
await clientConnections[UserName].Connection.Send( data, clientConnections[UserName].Destination ); await clientConnections[UserName].Connection.Send( data );
} }
public async Task SendServer<Packet>(Packet data) { public async Task SendServer<Packet>(Packet data) {
+9 -9
View File
@@ -8,13 +8,13 @@ using Mistox.Server;
namespace Mistox { namespace Mistox {
public class ServerInterface { public class ServerInterface {
public static MistoxServer ServerInstance; // Server Data public static MistoxServer ServerInstance; // Server Data
public static ServerListener Listener; // Server Listener public static ServerListener Listener; // Server Listener
public static ConcurrentDictionary<string, TcpClientConnection> Connections; // Server Connections public static ConcurrentDictionary<string, TcpClientConnection> Connections; // Server Connections
public event EventHandler onUserConnected; public event Action<TcpClientConnection> onUserConnected; // User connected event handler
public event EventHandler onReceive; public event Action<dynamic> onDataReceived; // Data received event handler
public event EventHandler onUserDisconnected; public event Action<TcpClientConnection> onUserDisconnected; // User disconnected event handler
public ServerInterface( int port, string serverName ) { public ServerInterface( int port, string serverName ) {
@@ -28,9 +28,9 @@ namespace Mistox {
Connections = new ConcurrentDictionary<string, TcpClientConnection>(); Connections = new ConcurrentDictionary<string, TcpClientConnection>();
// Setup the event handlers // Setup the event handlers
ServerInstance.onUserConnected += onUserConnected; ServerInstance.onUserConnected += (TcpClientConnection connectedUser) => { onUserConnected?.Invoke(connectedUser); };
ServerInstance.onReceived += onReceive; ServerInstance.onDataReceived += (dynamic data) => { onDataReceived?.Invoke(data); };
ServerInstance.onUserDisconnected += onUserDisconnected; ServerInstance.onUserDisconnected += (TcpClientConnection disconnectedUser) => { onUserDisconnected?.Invoke(disconnectedUser); };
// Start listening for connections and wire up the server // Start listening for connections and wire up the server
Listener = new ServerListener(); Listener = new ServerListener();
@@ -17,7 +17,7 @@ namespace Mistox {
} }
} }
public class mSerialize { public class Serializer {
static byte[] TBufferedData = []; static byte[] TBufferedData = [];
public static dynamic tReceive( byte [] BytesRead ) { public static dynamic tReceive( byte [] BytesRead ) {
+6 -12
View File
@@ -10,18 +10,12 @@ namespace Mistox.Server {
public int MaxClients { get; set; } = 10; // The max players per server public int MaxClients { get; set; } = 10; // The max players per server
public bool Alive { get; set; } = true; // Is the server running public bool Alive { get; set; } = true; // Is the server running
public event EventHandler onUserConnected; public event Action<TcpClientConnection> onUserConnected;
public void InvokeOnUserConnected(TcpClientConnection ConnectedUser){ public void InvokeUserConnected( TcpClientConnection user ){ onUserConnected?.Invoke( user ); }
onUserConnected?.Invoke(ConnectedUser, new EventArgs()); public event Action<dynamic> onDataReceived;
} public void InvokeDataReceived( dynamic data ){ onDataReceived?.Invoke( data ); }
public event EventHandler onReceived; public event Action<TcpClientConnection> onUserDisconnected;
public void InvokeOnReceived(dynamic DataPacket){ public void InvokeUserDisconnected( TcpClientConnection user ){ onUserDisconnected?.Invoke( user ); }
onReceived?.Invoke(DataPacket, new EventArgs());
}
public event EventHandler onUserDisconnected;
public void InvokeOnUserDisconnected(TcpClientConnection DisconnectedUser){
onUserDisconnected?.Invoke(DisconnectedUser, new EventArgs());
}
} }
} }
-1
View File
@@ -35,7 +35,6 @@ namespace Mistox.Server {
}; };
Console.WriteLine( "New User Connected" ); Console.WriteLine( "New User Connected" );
ServerInterface.ServerInstance.InvokeOnUserConnected( ServerInterface.Connections[connectionID] );
} }
} }
+11 -10
View File
@@ -7,28 +7,28 @@ namespace Mistox.Server {
public class TCPConnection : IDisposable { public class TCPConnection : IDisposable {
TcpClient _client; TcpClient _client;
string _connectionID; TcpClientConnection _connection;
public TCPConnection( TcpClient tcpClient, string ConnectionID ) { public TCPConnection( TcpClient tcpClient, string ConnectionID ) {
_client = tcpClient; _client = tcpClient;
_connectionID = ConnectionID;
_client.NoDelay = true; _client.NoDelay = true;
_connection = ServerInterface.Connections[ConnectionID];
ServerInterface.ServerInstance.InvokeUserConnected( ServerInterface.Connections[ConnectionID] );
// Start the receive thread // Start the receive thread
Thread receiveThread = new Thread(async () => await ReceiveThread() ); Thread receiveThread = new Thread(async () => await ReceiveThread() );
receiveThread.Start(); receiveThread.Start();
} }
public async Task ReceiveThread() { public async Task ReceiveThread() {
while( _client.Connected && ServerInterface.Connections[_connectionID].Connected ) { while( _client.Connected && _connection.Connected && ServerInterface.ServerInstance.Alive ) {
try { try {
ServerInterface.Connections[_connectionID].LastHeartbeat = DateTime.UtcNow; _connection.LastHeartbeat = DateTime.UtcNow;
byte[] StreamData = new byte[1024]; byte[] StreamData = new byte[1024];
int bytesRead = await _client.GetStream().ReadAsync(StreamData, 0, StreamData.Length); int bytesRead = await _client.GetStream().ReadAsync(StreamData, 0, StreamData.Length);
if( bytesRead > 0 ) { if( bytesRead > 0 ) {
dynamic data = mSerialize.tReceive( StreamData.Sub( 0, bytesRead ) ); dynamic data = Serializer.tReceive( StreamData.Sub( 0, bytesRead ) );
if( data != null ) { if( data != null ) {
ServerInterface.ServerInstance.InvokeOnReceived( data ); ServerInterface.ServerInstance.InvokeDataReceived( data );
} }
} }
} catch( Exception ) { } catch( Exception ) {
@@ -44,9 +44,10 @@ namespace Mistox.Server {
} }
public void Dispose() { public void Dispose() {
ServerInterface.Connections[_connectionID].Connected = false; _connection.Connected = false;
ServerInterface.ServerInstance.InvokeOnUserDisconnected( ServerInterface.Connections[_connectionID] ); ServerInterface.ServerInstance.InvokeUserDisconnected( _connection );
ServerInterface.Connections.TryRemove( _connectionID, out _ ); ServerInterface.ServerInstance.Alive = false;
ServerInterface.Connections.TryRemove( _connection.UserName, out _ );
} }
} }
} }