C#实现UDP组播

接收端:

public class UdpDemo
{
    public void Run()
    {
        Thread t = new Thread(new ThreadStart(RecvThread));
        t.IsBackground = true;
        t.Start();
        while (true)
        {
            Thread.Sleep(1000);
        }
    }

    public void RecvThread()
    {
        UdpClient client = new UdpClient(39841);
        client.JoinMulticastGroup(IPAddress.Parse("227.1.1.21"));
        IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
        while (true)
        {
            byte[] buf = client.Receive(ref remote);
            if (buf.Length == 0) continue;
            string msg = Encoding.UTF8.GetString(buf);
            Console.WriteLine("接收到消息--------------" + msg);

        }
    }
}

 

发送端:

    public class UdpDemo
    {
        public void Run()
        {
            UdpClient client = new UdpClient(39842);
            client.JoinMulticastGroup(IPAddress.Parse("227.1.1.21"));
            IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("227.1.1.21"), 39841);
            byte[] buf = Encoding.Default.GetBytes("Hello from multicast");
            while (true)
            {
                Console.WriteLine($"发送中");
                client.Send(buf, buf.Length, multicast);
                Thread.Sleep(1000);
            }
        }
  }

效果:

 

posted @ 2024-07-17 18:02  向萧  阅读(101)  评论(0编辑  收藏  举报