Files
GameServer/MistoxServer/Client/UDPReceiver.cs
T

58 lines
2.2 KiB
C#

using System;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Mistox.Client {
public class UDPReceiver : IDisposable {
private readonly MistoxClient _parent;
public UDPReceiver( MistoxClient parent) {
_parent = parent;
// Start the receive thread
Task.Run(ReceiveThread);
}
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();
// Try find the user
mUDPClient client = null;
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;
// Create the packet header
DataPacketHeader Header = new DataPacketHeader {
Type = (ushort)((dataPacket[0] << 8) | dataPacket[1]),
DataLength = (ushort)((dataPacket[2] << 8) | dataPacket[3])
};
// Slice out the data part of the packet
ReadOnlyMemory<byte> data = dataMemory.Slice(DataPacket.HeaderLength, Header.DataLength);
// Extract the object
dynamic buildObj = DataPacket.Deserialize( Header, data );
// Return the object
_parent.InvokeOnReceived( buildObj, client );
}
} catch( Exception e ) {
Console.WriteLine( "UDP Receive exception : " + e.Message );
}
}
}
public void Dispose() {
_parent.Alive = false;
}
}
}