C# UdpClient Simple Multicasting Broadcast Unsuccessful

40 views Asked by At

I am trying to setup the simplest implementation of Udp multicasting with C#. I am using UdpClient. The goal of this code is for a client to send some bytes and have them multicast to every connected client. For simplicity, I am not using any shared code. Here is the code I am using:

Server:

using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UDP.Server
{
    class Program
    {
        protected static UdpClient _udpClient;
        protected static IPEndPoint _localEp = new IPEndPoint(IPAddress.Parse("10.11.0.52"), 5000);
        protected static IPAddress _groupEp = IPAddress.Parse("234.5.6.7");

        static async Task Main(string[] args)
        {
            _udpClient = new UdpClient();
            _udpClient.Client.Bind(_localEp);
            _udpClient.JoinMulticastGroup(_groupEp);

            Console.WriteLine("Waiting for message...");
            while (true)
            {
                var message = await _udpClient.ReceiveAsync();
                Console.WriteLine(Encoding.UTF8.GetString(message.Buffer));
                await _udpClient.SendAsync(message.Buffer, message.Buffer.Length, new IPEndPoint(_groupEp, 5000));
            }
        }
    }
}

Client:

using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UDP.Client
{
    class Program
    {
        protected static UdpClient _udpClient = new UdpClient();
        protected static IPEndPoint _localEp = new IPEndPoint(IPAddress.Parse("10.11.0.52"), 5000);
        protected static IPAddress _groupEp = IPAddress.Parse("234.5.6.7");

        static async Task Main(string[] args)
        {
            Console.WriteLine("Hit enter to start the client");
            Console.ReadLine();

            _udpClient.Connect(_localEp);
            _udpClient.JoinMulticastGroup(_groupEp);

            _ = Task.Run(async () =>
            {
                while (true)
                {
                    var message = await _udpClient.ReceiveAsync();
                    Console.WriteLine(Encoding.UTF8.GetString(message.Buffer));
                }
            });

            while (true)
            {
                var bytes = Encoding.UTF8.GetBytes(Console.ReadLine()!);
                await _udpClient.SendAsync(bytes, bytes.Length);
            }
        }
    }
}

When this code runs, the server receives the message but does not transmit to all connected client.

0

There are 0 answers