using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; // Network Sync namespace Mistox.Client { public class mUDPClient : IDisposable { public string UserName { get; set; } = ""; // The remote players UserName public bool Alive { get; set; } = true; // Is the connection alive Socket _udpClient; IPEndPoint _remoteHost; MistoxClient _parent; public mUDPClient( MistoxClient parent, long RemoteIP, int Port ) { _parent = parent; _remoteHost = new IPEndPoint( RemoteIP, Port ); _udpClient = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); _udpClient.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true ); _udpClient.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, 128 ); _udpClient.Bind( new IPEndPoint( IPAddress.Any, Port ) ); _parent.Alive = true; Thread Client = new Thread(async() => { await ReceiveThread(); }); Client.Start(); } async Task ReceiveThread() { byte[] buffer = new byte[65535]; 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 int bytesRead = await _udpClient.ReceiveAsync( buffer ); // Create the data readers ReadOnlyMemory dataMemory = buffer.AsMemory(0, bytesRead); ReadOnlySpan dataPacket = dataMemory.Span; // Split apart the packet byte dataType = dataPacket[0]; ushort DataLength = (ushort)((dataPacket[1] << 8) | dataPacket[2]); ReadOnlyMemory data = dataMemory.Slice(DataPacket.HeaderLength, DataLength); // Extract the object dynamic buildObj = DataPacket.Deserialize( dataType, DataLength, data ); // Return the object _parent.InvokeOnReceived( buildObj ); } catch( Exception e ) { Console.WriteLine( "UDP Receive exception : " + e.Message ); } } } public async Task Send( T Data ) { byte[] byteData = DataPacket.Serialize( Data ); await _udpClient.SendToAsync( byteData, SocketFlags.None, _remoteHost ); } public void Dispose() { _parent.Alive = false; _udpClient.Close(); _udpClient = null; } } }