盈彩体育注册(中国)有限公司
盈彩体育注册(中国)有限公司 您所在的位置:网站首页 盈彩体育注册(中国)有限公司 Udp广播的发送与接收(C#+UdpClient) 上篇

Udp广播的发送与接收(C#+UdpClient) 上篇

2024-05-06 17:56:48| 来源: 网络整理

简介:

Udp广播消息用在局域网的消息传递很方便。本文使用UdpClient类在WPF下实现Udp广播收发

发送:

1 void MainWindow_Loaded(object sender, RoutedEventArgs e) 2 { 3 Loaded -= MainWindow_Loaded; 4 UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 0)); 5 IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 7788);//默认向全世界所有主机发送即可,路由器自动给你过滤,只发给局域网主机 6 String ip = "host:" + Dns.GetHostEntry(Dns.GetHostName()).AddressList.Last().ToString();//对外广播本机的ip地址 7 byte[] ipByte = Encoding.UTF8.GetBytes(ip); 8 DispatcherTimer dt = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };//每隔1秒对外发送一次广播 9 dt.Tick += delegate10 {11 client.Send(ipByte, ipByte.Length, endpoint);12 };13 dt.Start();14 }

接收:

1 void MainWindow_Loaded(object sender, RoutedEventArgs e) 2 { 3 Loaded -= MainWindow_Loaded; 4 UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 7788));//端口要与发送端相同 5 Thread thread = new Thread(receiveUdpMsg);//用线程接收,避免UI卡住 6 thread.IsBackground = true; 7 thread.Start(client); 8 } 9 void receiveUdpMsg(object obj)10 {11 UdpClient client = obj as UdpClient;12 IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);13 while (true)14 {15 client.BeginReceive(delegate(IAsyncResult result) {16 Console.WriteLine(result.AsyncState.ToString());//委托接收消息17 }, Encoding.UTF8.GetString(client.Receive(ref endpoint)));18 }19 }

效果:

 

 

  


【本文地址】 转载请注明 

最新文章

推荐文章

CopyRight 2018-2019 盈彩体育注册(中国)有限公司 版权所有 豫ICP备16040606号-1