接收端:
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); } } }
效果:
标签:UDP,组播,C#,IPAddress,IPEndPoint,client,new,buf,public From: https://www.cnblogs.com/dayang12525/p/18308030