System.Net.Sockets.UdpClient

Provides a simple client for sending and receiving UDP datagrams.

Introduction

The UdpClient class provides a UDP (User Datagram Protocol) socket that can be used for sending and receiving UDP datagrams. UDP is a connectionless protocol, meaning that it does not establish a connection before sending data. This makes it suitable for applications where speed is more important than reliability, such as real-time audio and video streaming, online gaming, and simple messaging protocols.

UdpClient simplifies the process of working with UDP sockets by abstracting away some of the lower-level details of the Socket class. It handles tasks like network address translation and provides convenient methods for sending and receiving data.

Constructors

public UdpClient()

Initializes a new instance of the UdpClient class.

public UdpClient(int port)

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

public UdpClient(string hostname, int port)

Initializes a new instance of the UdpClient class and establishes a default remote host and port for the client.

Key Methods

Receive(ref IPEndPoint remoteEP)

public byte[] Receive(ref System.Net.EndPoint remoteEP)

Receives a UDP datagram from the network and stores the data in the data buffer. This method blocks until a datagram is received.

Parameters:
  • remoteEP: An IPEndPoint that receives the network endpoint of the sender.
Returns: A byte array containing the data received.
Exceptions:
  • ObjectDisposedException: The UdpClient has been closed.
  • SocketException: An error occurred while accessing the socket.

Send(byte[] dgram, int bytes, IPEndPoint remoteEP)

public int Send(byte[] dgram, int bytes, System.Net.EndPoint remoteEP)

Sends UDP data to a remote host and port. This method is the preferred way to send data when you have not established a default remote host and port.

Parameters:
  • dgram: A byte array containing the data to send.
  • bytes: The number of bytes to send from the dgram buffer.
  • remoteEP: An IPEndPoint that specifies the remote host and port to which the data should be sent.
Returns: The number of bytes sent to the IPEndPoint.
Exceptions:
  • ObjectDisposedException: The UdpClient has been closed.
  • SocketException: An error occurred while accessing the socket.
  • ArgumentNullException: The dgram parameter is null.

Properties

Active: Gets a value indicating whether the UdpClient is active. This property is true if the client is bound to a port.

Client: Gets or sets the underlying Socket.

ExclusiveAddressUse: Gets or sets a value that indicates whether the UdpClient can exclusively use the network adapter.

Important Considerations

UDP is Unreliable: Unlike TCP, UDP does not guarantee delivery of datagrams. Datagrams may be lost, duplicated, or arrive out of order. Applications using UdpClient must be prepared to handle these conditions.

Blocking Operations: The Receive and Send methods can be blocking. If you need to perform other operations while waiting for data, consider using asynchronous methods like ReceiveAsync and SendAsync, or running these operations on a separate thread.

Buffer Management: Ensure that your receive buffer is large enough to accommodate the expected datagram size. Large datagrams may be truncated or cause errors if the buffer is too small.

Simple UDP Echo Client Example

This example demonstrates how to create a UdpClient, send a message, and receive a response.


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

public class UdpEchoClient
{
    public static async Task Main(string[] args)
    {
        string serverAddress = "127.0.0.1"; // Replace with your server's IP address
        int serverPort = 11000;            // Replace with your server's port

        using (UdpClient client = new UdpClient())
        {
            try
            {
                // Connect to the server (establishes a default remote endpoint)
                client.Connect(serverAddress, serverPort);
                Console.WriteLine($"Connected to {serverAddress}:{serverPort}");

                // Data to send
                string message = "Hello, UDP Server!";
                byte[] sendBytes = Encoding.ASCII.GetBytes(message);

                // Send data
                int bytesSent = await client.SendAsync(sendBytes, sendBytes.Length);
                Console.WriteLine($"Sent {bytesSent} bytes to server.");

                // Receive response
                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                byte[] receivedBytes = await client.ReceiveAsync();
                string receivedMessage = Encoding.ASCII.GetString(receivedBytes);

                Console.WriteLine($"Received from {remoteEndPoint}: {receivedMessage}");
            }
            catch (SocketException e)
            {
                Console.WriteLine($"SocketException: {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }
        }
    }
}