C# UDP组播客户端【UDPClient】
方式一 UdpClient udp = new UdpClient(5566);//要通过其进行通信的本地端口号。 5566是源端口 udp.JoinMulticastGroup(IPAddress.Parse("224.0.0.4"));//将 UdpClient 添加到多播组;IPAddress.Parse将IP地址字符串转换为IPAddress 实例 IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("224.0.0.4"), 7788); //将网络终结点表示为 IP 地址和端口号 7788是目的端口 Thread thread = new Thread(() => { while (true) { try { //定义一个字节数组,用来存放发送到远程主机的信息 Byte[] sendBytes = Encoding.Default.GetBytes("(" + DateTime.Now.ToLongTimeString() + ")节目预报:八点有大型晚会,请收听"); Console.WriteLine("(" + DateTime.Now.ToLongTimeString() + ")节目预报:八点有大型晚会,请收听"); //调用UdpClient对象的Send方法将UDP数据报发送到远程主机 udp.Send(sendBytes, sendBytes.Length, multicast);//将UDP数据报发送到位于指定远程终结点的主机 } catch (Exception ex) { //Console.WriteLine(ex.Message); } Thread.Sleep(2000); } }); thread.Start();//启动线程
方式二 try { UdpClient client = new UdpClient(5566); IPEndPoint multicastEndpoint = new IPEndPoint(IPAddress.Parse("234.5.6.7"), 11000); IPEndPoint multicastEndpoint2 = new IPEndPoint(IPAddress.Parse("234.5.6.9"), 11001); string message = "Hello, Multicast World!"; byte[] data = Encoding.UTF8.GetBytes(message); string message2 = "Hello, Multicast World22!"; byte[] data2 = Encoding.UTF8.GetBytes(message2); client.JoinMulticastGroup(IPAddress.Parse("234.5.6.8")); client.Send(data, data.Length, multicastEndpoint); client.Send(data2, data2.Length, multicastEndpoint2); client.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); }