简介:

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

发送:

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

接收:

         void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Loaded -= MainWindow_Loaded;
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, ));//端口要与发送端相同
Thread thread = new Thread(receiveUdpMsg);//用线程接收,避免UI卡住
thread.IsBackground = true;
thread.Start(client);
}
void receiveUdpMsg(object obj)
{
UdpClient client = obj as UdpClient;
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, );
while (true)
{
client.BeginReceive(delegate(IAsyncResult result) {
Console.WriteLine(result.AsyncState.ToString());//委托接收消息
}, Encoding.UTF8.GetString(client.Receive(ref endpoint)));
}
}

效果:

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

  

 
 
05-11 10:52