簡介:
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 += delegate 10 { 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 }
效果: