58 lines
2.2 KiB
C#
58 lines
2.2 KiB
C#
using System;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Mistox.Client {
|
|
public class UDPReceiver : IDisposable {
|
|
|
|
MistoxClient _parent;
|
|
|
|
public UDPReceiver( MistoxClient parent) {
|
|
_parent = parent;
|
|
Thread Client = new Thread(async() => { await ReceiveThread(); });
|
|
Client.Start();
|
|
}
|
|
|
|
async Task ReceiveThread() {
|
|
while( _parent.Alive ) {
|
|
try {
|
|
// Read the data out of the UDP packet with a buffer that has the maximum possible UDP packet size
|
|
// 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);
|
|
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);
|
|
|
|
// Extract the object
|
|
dynamic buildObj = DataPacket.Deserialize( dataType, DataLength, data );
|
|
|
|
// Return the object
|
|
_parent.InvokeOnReceived( buildObj, client );
|
|
|
|
}
|
|
} catch( Exception e ) {
|
|
Console.WriteLine( "UDP Receive exception : " + e.Message );
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Dispose() {
|
|
_parent.Alive = false;
|
|
}
|
|
}
|
|
} |