/// <summary> /// Asynchronously listens on the given port for a single packet. /// </summary> public static void Receive(int Port, ReceiveRawPacketHandler OnReceive) { using (UdpClient cli = new UdpClient(Port)) { Receive(cli, OnReceive); } }
/// <summary> /// Asynchronously listens on the given client for a single packet. /// </summary> public static void Receive(UdpClient Client, ReceiveRawPacketHandler OnReceive) { // Good job Microsoft, for making this so easy O_O while (true) { try { Client.BeginReceive(delegate(IAsyncResult ar) { lock (Client) { IPEndPoint end = new IPEndPoint(IPAddress.Any, 0); byte[] data; try { data = Client.EndReceive(ar, ref end); OnReceive(end, data); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.Shutdown) { return; } if (_CanIgnore(se)) { Receive(Client, OnReceive); } else { throw se; } } catch (ObjectDisposedException) { return; } } }, null); return; } catch (SocketException se) { if (!_CanIgnore(se)) { throw se; } } catch (ObjectDisposedException) { return; } } }