PROWAREtech
.NET: TCP/IP Sockets API Tutorial - Page 2 - UDP Sockets
Using the UdpClient class in C#.
UDP Sockets
UDP is more efficient than TCP having less overhead making it ideal for small communications between client and server. There is one
.NET class used by both the server and client: UdpClient
.
UdpClient for Server Applications
- Create a
UdpClient
object and specify the port to listen on. - Use the
Receive()
method to receive a datagram packet. - The
Receive()
method has a reference to anIPEndPoint
object as an argument. - Send and receive datagram packets using the
Send()
andReceive()
methods.
using System;
using System.Net;
using System.Net.Sockets;
class UdpServerExample
{
static void Main()
{
WaitClient();
}
static private void WaitClient()
{
int port = 1234;
Console.WriteLine("Listening...");
try
{
using (UdpClient client = new UdpClient(port))
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
byte[] bytes = client.Receive(ref ipep);
Console.WriteLine("Connected to client " + ipep.ToString());
// simply send an echo of the datagram that the client sent
client.Send(bytes, bytes.Length, ipep);
Console.WriteLine("{0} bytes sent", bytes.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
UdpClient for Client Applications
- Create a
UdpClient
object. - Use the
Send()
andReceive()
methods to exchange datagrams.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class UdpClientExample
{
static void Main()
{
ConnectToServer("hello");
while (true)
{
Console.Write("ENTER MESSAGE: ");
string echo = Console.ReadLine();
ConnectToServer(echo);
}
}
static private void ConnectToServer(string message)
{
string server = "localhost";
int port = 1234;
byte[] msg = Encoding.ASCII.GetBytes(message);
try
{
using (UdpClient client = new UdpClient())
{
// send the string to the server and it will be echoed back
client.Send(msg, msg.Length, server, port);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
byte[] recvd = client.Receive(ref ipep);
Console.WriteLine(Encoding.ASCII.GetString(recvd));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Comment