C# UDP Listener

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:

Ad Area

More
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();
                        }
                    }
                }

Ad Area

More

UDP does not check for data integrity or delivery, making it faster but less secure compared to TCP.

Ad Area

More
Author image
  • 16-09-2024
    Tags:

Comments

Leave a Comment

You may also like

Additional Questions and Answers

"Ctrl + F" allows you to quickly access questions and answers. You can add new questions by writing them in the...

LED Blinking with PIC Development Board

The PIC development board is a tool used for designing and testing prototypes of microcontrollers. Using the output pins available on the PIC board, y...