UdpListener Class

Listens for incoming UDP datagrams on a specified port.

The UdpListener class provides a simple way to listen for incoming User Datagram Protocol (UDP) datagrams on a specific port on the local computer. It is part of the System.Net.Sockets namespace.

Constructors

UdpListener(Int32 port)

public UdpListener(int port)

Initializes a new instance of the UdpListener class and binds it to the specified local port.

Parameters

UdpListener(IPEndPoint localEP)

public UdpListener(IPEndPoint localEP)

Initializes a new instance of the UdpListener class and binds it to the specified local endpoint.

Parameters

Methods

Start()

public void Start()

Starts listening for incoming UDP datagrams.

Remarks

This method must be called before any asynchronous or synchronous receive operations can be performed.

Stop()

public void Stop()

Stops listening for incoming UDP datagrams.

Receive()

public byte[] Receive()

Receives a UDP datagram.

Remarks

This is a synchronous method. It blocks the calling thread until a datagram is received.

Return Value

byte[] - A byte array containing the received UDP datagram data.

ReceiveFrom(EndPoint remoteEP)

public byte[] ReceiveFrom(out EndPoint remoteEP)

Receives a UDP datagram and the endpoint of the sender.

Remarks

This is a synchronous method. It blocks the calling thread until a datagram is received.

Parameters

Return Value

byte[] - A byte array containing the received UDP datagram data.

BeginReceive(AsyncCallback callback, Object state)

public IAsyncResult BeginReceive(AsyncCallback callback, object state)

Begins an asynchronous receive operation.

Parameters

Return Value

IAsyncResult - An IAsyncResult instance that references the asynchronous operation.

EndReceive(IAsyncResult asyncResult)

public byte[] EndReceive(IAsyncResult asyncResult)

Ends an asynchronous UDP datagram receive operation.

Parameters

Return Value

byte[] - A byte array containing the received UDP datagram data.

Properties

LocalEndpoint

public EndPoint LocalEndpoint get;

Gets the local endpoint to which the UdpListener is bound.

Client

public Socket Client get;

Gets the underlying socket for the UdpListener.

Example

The following example demonstrates how to create and use a UdpListener to receive UDP datagrams.


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

public class UdpReceiver
{
    private UdpClient udpClient;
    private bool isListening = false;

    public void StartListening(int port)
    {
        try
        {
            udpClient = new UdpClient(port);
            isListening = true;
            Console.WriteLine($"Listening on port {port}...");

            // Start a new thread to handle receiving data
            Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
            receiveThread.Start();
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error starting listener: {e.Message}");
        }
    }

    private void ReceiveData()
    {
        while (isListening)
        {
            try
            {
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                byte[] receivedBytes = udpClient.Receive(ref remoteEP);
                string receivedMessage = Encoding.ASCII.GetString(receivedBytes);

                Console.WriteLine($"Received from {remoteEP}: {receivedMessage}");
            }
            catch (SocketException sockEx)
            {
                if (isListening) // Only log if we're supposed to be listening
                {
                    Console.WriteLine($"Socket Exception: {sockEx.Message}");
                }
                break; // Exit loop on socket errors if not explicitly stopped
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error receiving data: {e.Message}");
            }
        }
        Console.WriteLine("Receive thread stopped.");
    }

    public void StopListening()
    {
        isListening = false;
        udpClient?.Close();
        Console.WriteLine("Listener stopped.");
    }

    public static void Main(string[] args)
    {
        UdpReceiver receiver = new UdpReceiver();
        int listenPort = 11000; // Example port

        receiver.StartListening(listenPort);

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

        receiver.StopListening();
    }
}
            

See Also