UdpReceiveEventArgs

System.Net.Sockets

Class UdpReceiveEventArgs

Represents data for an asynchronous UDP receive operation.

This class is used by the UdpClient class to provide information about received UDP datagrams.

public class UdpReceiveEventArgs

Inheritance

Constructors

Properties

Methods

Remarks

The UdpReceiveEventArgs class is primarily used internally by the UdpClient class. When a UDP datagram is received asynchronously, an instance of this class is created and populated with the received data, the sender's endpoint, and other relevant information. This instance is then passed to the callback method specified in the asynchronous receive operation.

Developers typically do not need to create instances of UdpReceiveEventArgs directly. Instead, they work with the instances provided by the UdpClient methods.

Examples

This section illustrates how UdpReceiveEventArgs is used in a typical asynchronous UDP receive scenario.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class UdpReceiver
{
    private UdpClient udpClient;
    private const int Port = 11000;

    public async Task StartReceivingAsync()
    {
        udpClient = new UdpClient(Port);
        Console.WriteLine($"UDP Receiver started on port {Port}");

        while (true)
        {
            try
            {
                UdpReceiveResult result = await udpClient.ReceiveAsync();
                // result.Buffer, result.BytesReceived, result.RemoteEndPoint are populated
                // from the UdpReceiveEventArgs implicitly.

                string receivedMessage = Encoding.ASCII.GetString(result.Buffer, 0, result.BytesReceived);
                IPEndPoint remoteEP = result.RemoteEndPoint;

                Console.WriteLine($"Received '{receivedMessage}' from {remoteEP.Address}:{remoteEP.Port}");

                // Example of sending a response (optional)
                byte[] sendBytes = Encoding.ASCII.GetBytes("Message received!");
                await udpClient.SendAsync(sendBytes, sendBytes.Length, remoteEP);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error receiving UDP packet: {ex.Message}");
                // Handle exceptions appropriately, perhaps break the loop or retry.
            }
        }
    }

    public void StopReceiving()
    {
        udpClient?.Close();
        Console.WriteLine("UDP Receiver stopped.");
    }

    public static async Task Main(string[] args)
    {
        UdpReceiver receiver = new UdpReceiver();
        // Run the receiver task. In a real application, you might manage its lifecycle.
        var receiverTask = receiver.StartReceivingAsync();

        Console.WriteLine("Press Enter to stop the receiver...");
        Console.ReadLine();

        receiver.StopReceiving();
        await receiverTask; // Wait for the receiver task to finish if it has a clean exit.
    }
}