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
Object
→ MarshalByRefObject
→ UdpClient
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:
Connect(IPEndPoint remoteEP)
: Connects to a remote host using anIPEndPoint
.Connect(string hostname, int port)
: Connects to a remote host using a hostname and port.Send(byte[] datagram, int bytes, IPEndPoint remoteEP)
: Sends UDP datagrams to a specified remote host.Send(byte[] datagram, int bytes)
: Sends UDP datagrams to the previously connected remote host.Receive(ref IPEndPoint remoteEP)
: Receives an incoming UDP datagram.Close()
: Closes theUdpClient
and releases all network resources.JoinMulticastGroup(IPAddress multicastAddr)
: Joins the specified multicast group.DropMulticastGroup(IPAddress multicastAddr)
: Leaves the specified multicast group.
Example Usage
Sending a UDP Datagram
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
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.