Provides a simple client for sending and receiving UDP datagrams.
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.
Initializes a new instance of the UdpClient class.
Initializes a new instance of the UdpClient class and binds it to the specified local port.
Initializes a new instance of the UdpClient class and establishes a default remote host and port for the client.
Receive(ref IPEndPoint remoteEP)Receives a UDP datagram from the network and stores the data in the data buffer. This method blocks until a datagram is received.
byte array containing the data received.
UdpClient has been closed.Send(byte[] dgram, int bytes, IPEndPoint 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.
byte array containing the data to send.
dgram buffer.
UdpClient has been closed.dgram parameter is null.
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.
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.
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}");
}
}
}
}