C# UdpClient简单多播广播不成功

问题描述 投票:0回答:0

我正在尝试使用 C# 设置最简单的 Udp 多播实现。我正在使用 UdpClient。此代码的目标是让客户端发送一些字节并将它们多播到每个连接的客户端。为简单起见,我没有使用任何共享代码。这是我正在使用的代码:

服务员:

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

客户:

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

当此代码运行时,服务器接收消息但不会传输到所有连接的客户端。

c# udp multicast udpclient multicasting
© www.soinside.com 2019 - 2024. All rights reserved.