简介:
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 }