C#实现UDP组播

来源:互联网 发布:linux exec函数 编辑:程序博客网 时间:2024/04/28 21:16
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Net;  
  6. using System.Net.Sockets;  
  7. using System.Threading;  
  8.   
  9. namespace Test  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             UdpClient client = new UdpClient(5566);  
  16.             client.JoinMulticastGroup(IPAddress.Parse("234.5.6.7"));  
  17.             IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("234.5.6.7"), 7788);  
  18.             byte[] buf = Encoding.Default.GetBytes("Hello from multicast");  
  19.             Thread t = new Thread(new ThreadStart(RecvThread));  
  20.             t.IsBackground = true;  
  21.             t.Start();  
  22.             while (true)  
  23.             {  
  24.                 client.Send(buf, buf.Length, multicast);  
  25.                 Thread.Sleep(1000);  
  26.             }  
  27.         }  
  28.   
  29.         static void RecvThread()  
  30.         {  
  31.             UdpClient client = new UdpClient(7788);  
  32.             client.JoinMulticastGroup(IPAddress.Parse("234.5.6.7"));  
  33.             IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("234.5.6.7"), 5566);  
  34.             while (true)  
  35.             {  
  36.                 byte[] buf = client.Receive(ref multicast);  
  37.                 string msg = Encoding.Default.GetString(buf);  
  38.                 Console.WriteLine(msg);  
  39.             }  
  40.         }  
  41.     }  
  42. }  

组播地址为 224.0.0.0 ~ 239.255.255.255,其中 224.0.0.0~224.255.255.255 不建议在用户程序中使用,因为它们一般都有特殊用途。
0 0
原创粉丝点击