Split out the UDP listener for a single instance
This commit is contained in:
1 parent
6931846a64
commit
d3d437b0c8
5 files changed
+127
-68
No files matched your search
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
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 );
|
||||
|
||||
// Map the IPEndPoint to a user
|
||||
IPEndPoint endpoint = udpPacket.RemoteEndPoint;
|
||||
|
||||
// Return the object
|
||||
_parent.InvokeOnReceived( buildObj, udpPacket.RemoteEndPoint );
|
||||
|
||||
}
|
||||
} catch( Exception e ) {
|
||||
Console.WriteLine( "UDP Receive exception : " + e.Message );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
_parent.Alive = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user