C# udp 广播接收 发送

C# udp 广播接收 发送

http://blog.sina.com.cn/s/blog_542bad910102w0er.html

 (2016-01-24 17:10:49)
  分类: VCC#

向255.255.255.255发送UPD数据包即为UDP广播,接收端只需绑定UDP广播的端口号即可得到数据

 

[csharp] view plain copy
 
  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(new IPEndPoint(IPAddress.Any, 0));  
  16.             IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 7788);  
  17.             byte[] buf = Encoding.Default.GetBytes("Hello from UDP broadcast");  
  18.             Thread t = new Thread(new ThreadStart(RecvThread));  
  19.             t.IsBackground = true;  
  20.             t.Start();  
  21.             while (true)  
  22.             {  
  23.                 client.Send(buf, buf.Length, endpoint);  
  24.                 Thread.Sleep(1000);  
  25.             }  
  26.         }  
  27.   
  28.         static void RecvThread()  
  29.         {  
  30.             UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 7788));  
  31.             IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);  
  32.             while (true)  
  33.             {  
  34.                 byte[] buf = client.Receive(ref endpoint);  
  35.                 string msg = Encoding.Default.GetString(buf);  
  36.                 Console.WriteLine(msg);  
  37.             }  
  38.         }  
  39.     }  
  40. }  

1

0

 
阅读(622)┊ 评论 (0)收藏(0) 转载(0) ┊ 喜欢 打印举报
已投稿到:

 

 

 

posted @ 2017-10-23 10:54  sky20080101  阅读(380)  评论(0)    收藏  举报