Tons of minor fixes
This commit is contained in:
1 parent
873a6fa455
commit
37a6b5d59b
12 files changed
+219
-147
No files matched your search
@@ -2,35 +2,51 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
using Mistox.ResevedPackets;
|
||||
|
||||
namespace Mistox.Client {
|
||||
|
||||
public class MistoxClient {
|
||||
|
||||
public string ServerName { get; set; } = ""; // The Name of the server
|
||||
public string ServerName { get; private set; } = ""; // The Name of the server
|
||||
public string UserName { get; private set; } = ""; // My UserName
|
||||
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 bool isAuthenticated { get; set; } = false; // Is the server authenticated
|
||||
public ConcurrentDictionary<IPEndPoint, mUDPClient> clientConnections; // UserName, Connection
|
||||
|
||||
public mTCPClient ServerConnection {get; private set; } // Global TCP Server Connection
|
||||
public UdpClient ClientSocket { get; private set; } // Global UDP Sender
|
||||
public UDPReceiver UdpReceiver { get; private set; } // Global UDP Receiver
|
||||
private readonly string ConnectionKey = ""; // Server Connection Key
|
||||
|
||||
public MistoxClient(IPEndPoint Server) {
|
||||
public MistoxClient(string userName, string connectionKey, IPEndPoint Server) {
|
||||
// Create and listen on UDP
|
||||
ClientSocket = new UdpClient( Server.Port );
|
||||
UdpReceiver = new UDPReceiver( this );
|
||||
UserName = userName;
|
||||
ConnectionKey = connectionKey;
|
||||
|
||||
// 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" );
|
||||
Alive = true;
|
||||
} catch( Exception e ) {
|
||||
Console.WriteLine( "An error has occured with the connection to the server. Error { " );
|
||||
Console.WriteLine( e.ToString() );
|
||||
Console.WriteLine( "}" );
|
||||
Alive = false;
|
||||
}
|
||||
Alive = true;
|
||||
}
|
||||
|
||||
public async Task TryAuth() {
|
||||
Console.WriteLine("Attempting to authenticate against the server...");
|
||||
await ServerConnection.Send(new UserAuthPacket {
|
||||
UserName = UserName,
|
||||
ConnectionKey = ConnectionKey
|
||||
});
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
@@ -38,27 +54,33 @@ namespace Mistox.Client {
|
||||
/////////////////////////////
|
||||
|
||||
public void UserConnected(UserConnectedPacket packet) {
|
||||
mUDPClient user = new mUDPClient(this, packet.ClientIPAddress, packet.ClientPort) {
|
||||
IPEndPoint remoteUser = new IPEndPoint(packet.ClientIPAddress, packet.ClientPort);
|
||||
mUDPClient user = new mUDPClient(this, remoteUser) {
|
||||
UserName = packet.UserName
|
||||
};
|
||||
clientConnections[user.GetConnectionKey()] = user;
|
||||
clientConnections[remoteUser] = user;
|
||||
InvokeOnUserConnected(user);
|
||||
}
|
||||
|
||||
public void UserDisconnected(UserDisconnectedPacket packet) {
|
||||
mUDPClient client;
|
||||
bool found = clientConnections.TryGetValue(packet.ConnectionKey, out client);
|
||||
if (found) {
|
||||
mUDPClient client = null;
|
||||
foreach(mUDPClient cur in clientConnections.Values) {
|
||||
if (cur.UserName.ToLower() == packet.UserName.ToLower()) {
|
||||
client = cur;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (client != null) {
|
||||
InvokeOnUserDisconnected( client );
|
||||
client.Alive = false;
|
||||
client.Dispose();
|
||||
clientConnections[packet.ConnectionKey] = null;
|
||||
clientConnections[client._remoteHost] = null;
|
||||
}
|
||||
}
|
||||
|
||||
/////////////////////////////
|
||||
// Events
|
||||
/////////////////////////////
|
||||
/////////////////////////////
|
||||
// Events
|
||||
/////////////////////////////
|
||||
|
||||
public event Action<dynamic> onDataReceived;
|
||||
public void InvokeOnReceived(dynamic DataPacket, mUDPClient remote = null){
|
||||
@@ -81,6 +103,11 @@ namespace Mistox.Client {
|
||||
public event Action onServerConnected;
|
||||
public void InvokeOnServerConnected(){
|
||||
Alive = true;
|
||||
Task.Run(async () => {
|
||||
try {
|
||||
await TryAuth();
|
||||
} catch {}
|
||||
});
|
||||
onServerConnected?.Invoke();
|
||||
}
|
||||
|
||||
|
||||
@@ -9,16 +9,17 @@ using System.Threading.Tasks;
|
||||
namespace Mistox.Client {
|
||||
public class mTCPClient : IDisposable {
|
||||
|
||||
TcpClient _connection;
|
||||
MistoxClient _parent;
|
||||
private readonly TcpClient _connection;
|
||||
private readonly MistoxClient _parent;
|
||||
private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
|
||||
|
||||
public mTCPClient( MistoxClient parent, IPEndPoint ServerAddress ) {
|
||||
_connection = new TcpClient( AddressFamily.InterNetwork );
|
||||
_connection.NoDelay = true;
|
||||
_connection.Connect( ServerAddress );
|
||||
_parent.InvokeOnServerConnected();
|
||||
Thread RThread = new Thread(async () => { await ReceiveThread(); });
|
||||
RThread.Start();
|
||||
// Start the receive thread
|
||||
Task.Run(ReceiveThread);
|
||||
}
|
||||
|
||||
async Task ReceiveThread() {
|
||||
@@ -32,19 +33,21 @@ namespace Mistox.Client {
|
||||
await ns.ReadExactlyAsync(headerBuffer, 0, 3);
|
||||
|
||||
// Parse the header
|
||||
byte packetbyte = headerBuffer[0];
|
||||
ushort dataLength = (ushort)((headerBuffer[1] << 8) | headerBuffer[2]);
|
||||
DataPacketHeader Header = new DataPacketHeader {
|
||||
Type = headerBuffer[0],
|
||||
DataLength = (ushort)((headerBuffer[1] << 8) | headerBuffer[2])
|
||||
};
|
||||
|
||||
// Make sure the data looks valid
|
||||
if (dataLength > payloadBuffer.Length) {
|
||||
if (Header.DataLength > payloadBuffer.Length) {
|
||||
throw new Exception("Incoming TCP payload is too large for the pre-allocated buffer.");
|
||||
}
|
||||
|
||||
// Read off the data
|
||||
await ns.ReadExactlyAsync(payloadBuffer, 0, dataLength);
|
||||
await ns.ReadExactlyAsync(payloadBuffer, 0, Header.DataLength);
|
||||
|
||||
// Create the dataobject
|
||||
dynamic dataobject = DataPacket.Deserialize( packetbyte, dataLength, payloadBuffer.AsMemory(DataPacket.HeaderLength, dataLength) );
|
||||
dynamic dataobject = DataPacket.Deserialize( Header, payloadBuffer.AsMemory(DataPacket.HeaderLength, Header.DataLength) );
|
||||
|
||||
// Return the object
|
||||
_parent.InvokeOnReceived(dataobject);
|
||||
@@ -60,13 +63,18 @@ namespace Mistox.Client {
|
||||
|
||||
public async Task Send<T>(T packet) {
|
||||
byte[] data = DataPacket.Serialize( packet );
|
||||
await _connection.GetStream().WriteAsync( data, 0, data.Length );
|
||||
await _sendLock.WaitAsync();
|
||||
try {
|
||||
await _connection.GetStream().WriteAsync( data, 0, data.Length );
|
||||
} finally {
|
||||
_sendLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
_parent.InvokeOnServerDisconnected();
|
||||
_connection.Close();
|
||||
_connection = null;
|
||||
_connection.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Mistox.Client {
|
||||
@@ -7,38 +8,31 @@ namespace Mistox.Client {
|
||||
|
||||
public string UserName { get; set; } = ""; // The remote players UserName
|
||||
public bool Alive { get; set; } = true; // Is the connection alive
|
||||
public IPEndPoint IPAddress { get; set; } // The remote IP Address
|
||||
public IPEndPoint _remoteHost { get; set; } // The remote IP Address
|
||||
|
||||
IPEndPoint _remoteHost;
|
||||
MistoxClient _parent;
|
||||
private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
|
||||
private readonly MistoxClient _parent;
|
||||
|
||||
public mUDPClient( MistoxClient parent, IPAddress RemoteIP, int Port ) {
|
||||
public mUDPClient( MistoxClient parent, IPEndPoint remoteHost ) {
|
||||
_parent = parent;
|
||||
_remoteHost = new IPEndPoint( RemoteIP, Port );
|
||||
_remoteHost = remoteHost;
|
||||
_parent.Alive = true;
|
||||
}
|
||||
|
||||
public async Task Send<T>( T Data ) {
|
||||
byte[] byteData = DataPacket.Serialize( Data );
|
||||
await _parent.ClientSocket.SendAsync( byteData, byteData.Length, _remoteHost );
|
||||
}
|
||||
|
||||
public static UInt128 GetConnectionKey(IPAddress ipAddress) {
|
||||
byte[] bytes = ipAddress.GetAddressBytes();
|
||||
if (bytes.Length == 4) {
|
||||
bytes = ipAddress.MapToIPv6().GetAddressBytes();
|
||||
await _sendLock.WaitAsync();
|
||||
try {
|
||||
await _parent.ClientSocket.SendAsync( byteData, byteData.Length, _remoteHost );
|
||||
} finally {
|
||||
_sendLock.Release();
|
||||
}
|
||||
return BitConverter.ToUInt128(bytes, 0);
|
||||
}
|
||||
|
||||
public UInt128 GetConnectionKey() {
|
||||
return GetConnectionKey( IPAddress.Address );
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
_parent.Alive = false;
|
||||
_parent.ClientSocket.Close();
|
||||
_parent.ClientSocket = null;
|
||||
_parent.ClientSocket.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Mistox.Client {
|
||||
public class UDPReceiver : IDisposable {
|
||||
|
||||
MistoxClient _parent;
|
||||
private readonly MistoxClient _parent;
|
||||
|
||||
public UDPReceiver( MistoxClient parent) {
|
||||
_parent = parent;
|
||||
Thread Client = new Thread(async() => { await ReceiveThread(); });
|
||||
Client.Start();
|
||||
// Start the receive thread
|
||||
Task.Run(ReceiveThread);
|
||||
}
|
||||
|
||||
async Task ReceiveThread() {
|
||||
@@ -21,25 +20,26 @@ namespace Mistox.Client {
|
||||
// As UDP reads the whole next packet then drops. Im guaranteed to receive 1 packet at a time
|
||||
UdpReceiveResult udpPacket = await _parent.ClientSocket.ReceiveAsync();
|
||||
|
||||
// Compute the connectionKey
|
||||
UInt128 ConnectionKey = mUDPClient.GetConnectionKey(udpPacket.RemoteEndPoint.Address);
|
||||
|
||||
// Try find the user
|
||||
mUDPClient client = null;
|
||||
bool clientExists = _parent.clientConnections.TryGetValue(ConnectionKey, out client);
|
||||
bool clientExists = _parent.clientConnections.TryGetValue(udpPacket.RemoteEndPoint, out client);
|
||||
if (clientExists) {
|
||||
|
||||
// Create the data readers
|
||||
ReadOnlyMemory<byte> dataMemory = udpPacket.Buffer.AsMemory();
|
||||
ReadOnlySpan<byte> dataPacket = dataMemory.Span;
|
||||
|
||||
// Split apart the packet
|
||||
byte dataType = dataPacket[0];
|
||||
ushort DataLength = (ushort)((dataPacket[1] << 8) | dataPacket[2]);
|
||||
ReadOnlyMemory<byte> data = dataMemory.Slice(DataPacket.HeaderLength, DataLength);
|
||||
// Create the packet header
|
||||
DataPacketHeader Header = new DataPacketHeader {
|
||||
Type = dataPacket[0],
|
||||
DataLength = (ushort)((dataPacket[1] << 8) | dataPacket[2])
|
||||
};
|
||||
|
||||
// Slice out the data part of the packet
|
||||
ReadOnlyMemory<byte> data = dataMemory.Slice(DataPacket.HeaderLength, Header.DataLength);
|
||||
|
||||
// Extract the object
|
||||
dynamic buildObj = DataPacket.Deserialize( dataType, DataLength, data );
|
||||
dynamic buildObj = DataPacket.Deserialize( Header, data );
|
||||
|
||||
// Return the object
|
||||
_parent.InvokeOnReceived( buildObj, client );
|
||||
|
||||
Reference in new issue
Block a user