UDP (User Datagram Protocol) is a protocol that allows data packets to be sent directly to their destination. Data is sent as BYTES and needs to be converted to ASCII code.
To write a UDP listener application in C#, use the UdpClient class. Here is an example:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main()
{
string ipAddress = "127.0.0.1";
int port = 1234;
UdpClient listener = new UdpClient(new IPEndPoint(IPAddress.Parse(ipAddress), port));
try
{
while (true)
{
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] receivedBytes = listener.Receive(ref remoteIpEndPoint);
string receivedMessage = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("Received message: " + receivedMessage);
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
listener.Close();
}
}
}
UDP does not check for data integrity or delivery, making it faster but less secure compared to TCP.
Comments
Leave a Comment