C# UDP Communication

Communicating across UDP is useful for peer-to-peer and intermittent connections, where TCP is not practical. Below is an example of communicating via UDP using C#.

public class MyUdpService
{
    private UdpClient udpClient;
    private IPEndPoint remoteIpEndPoint;
    private boolean started;

    // Communicate with a specific IP address
    public MyUdpService(String ipAddress, int port)
    {
        Start(IPAddress.Parse(ipAddress), port);
    }

    // Broadcast to any IP address
    public MyUdpService(int port)
    {
        Start(IPAddress.Broadcast, port);
    }

    private Start(IPAddress ipAddress, int port)
    {
        started = true;

        udpClient = new UdpClient(port);
        remoteIpEndPoint = new IPEndPoint(ipAddress, port);

        // Start the UDP receiver thread
        Task.Run(Receive, cancellationToken);
    }

    public void Stop()
    {
        started = false;
    }

    public void Send(string message)
    {
        try
        {
            var bytes = Encoding.UTF8.GetBytes(message);
            udpClient.Send(bytes, bytes.Length, remoteIpEndPoint);
            Console.WriteLine("Sent message: " + message);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    private void Receive()
    {
        while (started)
        {
            try
            {
                var bytes = udpClient.Receive(ref remoteIpEndPoint);
                var message = Encoding.UTF8.GetString();
                Console.WriteLine("Received message: " + message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

To use it:

public void test()
{
    var port = 12345;
    var ipAddress = "10.0.0.100";
    var udp = new UdpService(port, ipAddress);
    udp.Send("Hello!");
    Console.ReadLine();
    udp.Stop();
}

You may also like...

Popular Posts