This section provides sample code demonstrating the use of User Datagram Protocol (UDP) for network communication on Windows. UDP is a connectionless transport layer protocol that offers low overhead and fast transmission, making it suitable for applications where speed is critical and occasional packet loss is acceptable, such as streaming media, online gaming, and DNS.
This sample demonstrates how to create a simple UDP client application that sends datagrams to a specified server address and port.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpClientSample
{
public static void Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Usage: UdpClientSample <server_ip> <server_port> <message>");
return;
}
string serverIp = args[0];
int serverPort = int.Parse(args[1]);
string message = args[2];
try
{
using (UdpClient client = new UdpClient())
{
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
byte[] sendBytes = Encoding.ASCII.GetBytes(message);
Console.WriteLine($"Sending message: '{message}' to {serverIp}:{serverPort}");
client.Send(sendBytes, sendBytes.Length, serverEndPoint);
// Optionally, receive a response
byte[] receivedBytes = client.Receive(ref serverEndPoint);
string receivedMessage = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine($"Received response: '{receivedMessage}' from {serverEndPoint.Address}:{serverEndPoint.Port}");
}
}
catch (SocketException e)
{
Console.WriteLine($"SocketException: {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
}
This sample demonstrates how to create a basic UDP server that listens for incoming datagrams and echoes them back to the client.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpServerSample
{
public static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: UdpServerSample <port>");
return;
}
int port = int.Parse(args[0]);
try
{
using (UdpClient server = new UdpClient(port))
{
Console.WriteLine($"UDP Server listening on port {port}...");
IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
byte[] receivedBytes = server.Receive(ref clientEndPoint);
string receivedMessage = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine($"Received from {clientEndPoint.Address}:{clientEndPoint.Port}: '{receivedMessage}'");
// Echo the message back to the client
byte[] sendBytes = Encoding.ASCII.GetBytes($"Echo: {receivedMessage}");
server.Send(sendBytes, sendBytes.Length, clientEndPoint);
Console.WriteLine($"Sent echo back to {clientEndPoint.Address}:{clientEndPoint.Port}");
}
}
}
catch (SocketException e)
{
Console.WriteLine($"SocketException: {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
}