create a udp server in csharp

To create a UDP server in C#, you can use the UdpClient class provided by the System.Net.Sockets namespace. Below is an example code that shows you how to create a simple UDP server that listens for messages from a client and echoes them back:

main.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class UDPServer
{
    static void Main(string[] args)
    {
        // Create a new UdpClient that listens on port 8000
        UdpClient server = new UdpClient(8000);

        try
        {
            Console.WriteLine("UDP server listening on port 8000...");

            while (true)
            {
                // Receive a message from a client
                IPEndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
                byte[] buffer = server.Receive(ref clientEP);
                string message = Encoding.ASCII.GetString(buffer);

                Console.WriteLine("Received message: {0} from {1}", message, clientEP);

                // Echo the message back to the client
                server.Send(buffer, buffer.Length, clientEP);
                
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            // Close the UDP socket
            server.Close();
        }
    }
}
1081 chars
42 lines

This code creates a new UdpClient that listens on port 8000. It then enters a loop where it waits for messages to arrive from clients. When a message is received, it is echoed back to the client using the Send() method of the UdpClient class.

gistlibby LogSnag