using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; // Network Sync namespace MistoxServer.Client { public class mUDPClient : IDisposable { public event EventHandler onReceived; Socket udpClient; bool Alive; int Port; public mUDPClient( IPEndPoint ServerAddress ) { 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, ServerAddress.Port ) ); Alive = true; Port = ServerAddress.Port; Thread Client = new Thread(async() => { await ReceiveThread(); }); Client.Start(); } async Task ReceiveThread() { while( Alive ) { try { byte[] buffer = new byte[1024]; int bytesRead = await udpClient.ReceiveAsync( buffer ); dynamic data = mSerialize.uReceive( buffer.Sub(0, bytesRead) ); if( data != null ) { onReceived?.Invoke( data, new EventArgs() ); } } catch( Exception ) { } } } public async Task Send( T Data, IPEndPoint remoteHost ) { byte[] byteData = DataPacket.Serialize( Data ); await udpClient.SendToAsync( byteData, SocketFlags.None, new IPEndPoint( remoteHost.Address, Port ) ); } public void Dispose() { Alive = false; udpClient.Close(); udpClient = null; } } }