发送组播消息:
static void Main(string[] args) { UdpClient udpClient = new UdpClient(); IPEndPoint broadcastIp = new IPEndPoint(IPAddress.Parse("224.0.0.122"), 4533); int i = 0; while (true) { Console.WriteLine(i); byte[] b = Encoding.UTF8.GetBytes("我在组播消息" + i++); udpClient.Send(b, b.Length, broadcastIp); System.Threading.Thread.Sleep(1000); } }
接收组播消息:
static void Main(string[] args)
{
UdpClient receiveUdpClient = new UdpClient(4533);
receiveUdpClient.JoinMulticastGroup(IPAddress.Parse("224.0.0.122"));
receiveUdpClient.Ttl = 50;
IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
byte[] r = receiveUdpClient.Receive(ref remoteIP);
Console.WriteLine(Encoding.UTF8.GetString(r));
}
}