UdpClient Class

Provides a UDP (User Datagram Protocol) service.

Note: UDP is a connectionless protocol. Unlike TCP, it does not establish a connection before sending data, nor does it guarantee delivery or order of packets. It is suitable for applications where speed is critical and some data loss is acceptable.

Namespace

System.Net.Sockets

Inheritance

ObjectMarshalByRefObjectUdpClient

Summary

The UdpClient class provides a simple interface for sending and receiving UDP datagrams. It allows you to send UDP packets to a specified remote host and port, and to receive incoming UDP datagrams. It handles the underlying socket creation and management, simplifying UDP communication.

Constructors

Constructor Description
UdpClient() Initializes a new instance of the UdpClient class.
UdpClient(int port) Initializes a new instance of the UdpClient class and binds it to the specified local port.
UdpClient(IPEndPoint localEP) Initializes a new instance of the UdpClient class and binds it to the specified local endpoint.
UdpClient(string hostname, int port) Initializes a new instance of the UdpClient class and connects it to a remote host and port.

Properties

Property Description
Active Gets a value indicating whether the UdpClient is active.
Client Gets or sets the underlying Socket for the UdpClient.
ExclusiveAddressUse Gets or sets a value that specifies whether the UdpClient allows other applications to bind to the same port.
Available Gets the number of bytes available to be read from the network buffer.

Methods

Key methods include:

Example Usage

Sending a UDP Datagram

This example demonstrates sending a simple message to a remote host.

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

public class UdpSender
{
    public static void SendMessage(string ipAddress, int port, string message)
    {
        using (UdpClient client = new UdpClient())
        {
            try
            {
                byte[] data = Encoding.UTF8.GetBytes(message);
                IPEndPoint targetEP = new IPEndPoint(IPAddress.Parse(ipAddress), port);

                client.Send(data, data.Length, targetEP);
                Console.WriteLine($"Sent '{message}' to {targetEP}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending message: {ex.Message}");
            }
        }
    }

    public static void Main(string[] args)
    {
        SendMessage("127.0.0.1", 11000, "Hello UDP!");
    }
}
        

Receiving UDP Datagrams

This example shows how to listen for incoming UDP datagrams on a specific port.

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

public class UdpReceiver
{
    private const int ListenPort = 11000;
    private static volatile bool stopListening = false;

    public static void StartListening()
    {
        UdpClient listener = null;
        try
        {
            listener = new UdpClient(ListenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, ListenPort);

            Console.WriteLine($"Listening for UDP datagrams on port {ListenPort}...");

            while (!stopListening)
            {
                byte[] bytes = listener.Receive(ref groupEP);
                string message = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                Console.WriteLine($"Received '{message}' from {groupEP}");
            }
        }
        catch (SocketException se)
        {
            Console.WriteLine($"SocketException in receiver: {se.ErrorCode} {se.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error in receiver: {ex.Message}");
        }
        finally
        {
            listener?.Close();
            Console.WriteLine("Receiver stopped.");
        }
    }

    public static void Stop()
    {
        stopListening = true;
    }

    public static void Main(string[] args)
    {
        Thread receiverThread = new Thread(StartListening);
        receiverThread.Start();

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

        Stop();
        receiverThread.Join(); // Wait for the receiver thread to finish
    }
}
        

Tip: For reliable asynchronous operations, consider using the asynchronous methods like SendAsync and ReceiveAsync available in newer .NET versions.

See Also