C# > Networking > HTTP and Sockets > UdpClient Usage
Simple UDP Client and Server Communication
This code demonstrates a basic UDP client and server in C#. UDP is a connectionless protocol, meaning there's no persistent connection established between the client and server. Data is sent in discrete packets. The example showcases how a client sends a message to a server, and the server receives and responds to it.
Concepts Behind the Snippet
UDP (User Datagram Protocol) is a communication protocol that doesn't establish a connection before sending data. This makes it faster than TCP (Transmission Control Protocol) but also less reliable, as there's no guarantee of delivery or order. The UdpClient
class in C# provides a simple way to send and receive UDP packets. The server listens on a specific port and responds to incoming messages. The client sends messages to the server's IP address and port.
UDP Server Implementation
This code sets up a UDP server listening on port 11000. It uses a UdpClient
to receive data. The Receive
method blocks until a UDP packet is received. The ref groupEP
parameter is populated with the IP address and port of the sender. After receiving the message, it constructs a response and sends it back to the client using the Send
method.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UDPServer
{
private const int listenPort = 11000;
public static void Main()
{
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
Console.WriteLine("Waiting for broadcast...");
while (true)
{
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine($"Received broadcast from {groupEP} :");
Console.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
string receivedMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
string responseMessage = "Server received: " + receivedMessage;
byte[] responseBytes = Encoding.ASCII.GetBytes(responseMessage);
listener.Send(responseBytes, responseBytes.Length, groupEP);
}
}
catch (SocketException e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
}
UDP Client Implementation
This code sets up a UDP client that sends a message to the server running on 127.0.0.1 (localhost) at port 11000. It creates a UdpClient
and an IPEndPoint
representing the server's address. The Send
method sends the message. Then, it waits to receive the server's response using Receive
and prints the received data. The client also closes the UdpClient in a finally block to ensure resources are released.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UDPClient
{
public static void Main()
{
UdpClient client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
try
{
string message = "Hello Server!";
byte[] sendbuf = Encoding.ASCII.GetBytes(message);
client.Send(sendbuf, sendbuf.Length, ep);
Console.WriteLine("Message sent to the broadcast address");
byte[] receiveBytes = client.Receive(ref ep);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine($"Received: {returnData}");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
client.Close();
}
}
}
Real-Life Use Case
UDP is commonly used in applications where speed is more important than guaranteed delivery, such as online gaming, video streaming, DNS lookups, and VoIP (Voice over IP). For example, in a multiplayer game, it's acceptable to lose occasional packets representing player movements, as the game state is constantly updated.
Best Practices
SocketException
.client.Client.ReceiveTimeout = milliseconds;
BeginReceive
, EndReceive
, BeginSend
, EndSend
) to avoid blocking the main thread.
Interview Tip
Be prepared to discuss the differences between UDP and TCP. Highlight UDP's speed and connectionless nature, as well as its suitability for applications where occasional packet loss is acceptable. Also, know how to handle exceptions and manage resources properly (closing the UdpClient
).
When to Use UDP
Use UDP when:
Memory Footprint
The memory footprint of a UdpClient
is relatively small. It mainly consists of the socket resources and buffers for sending and receiving data. However, it's important to release the resources by calling Close()
when the client is no longer needed.
Alternatives
HttpClient
) if you're communicating with a web server.
Pros
Cons
FAQ
-
What is the maximum size of a UDP packet?
The theoretical maximum size of a UDP packet is 65,535 bytes (including the header). However, in practice, the maximum payload size is limited by the network's MTU (Maximum Transmission Unit) and is often around 512 bytes or less to avoid fragmentation. IPv4 has a minimum MTU of 576 bytes, and IPv6 has a minimum MTU of 1280 bytes. -
How do I handle packet loss in UDP?
Packet loss is inherent in UDP. You can implement your own reliability mechanisms, such as acknowledgements, sequence numbers, and retransmission timers, but this effectively reimplements parts of TCP. Alternatively, you can accept the packet loss if your application can tolerate it. -
How do I determine the sender's IP address and port in a UDP server?
TheReceive
method of theUdpClient
class populates theIPEndPoint
object passed by reference with the sender's IP address and port.