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


    简介:

      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         }


    效果:

      

     
     
  • 相关阅读:
    How to render client report definition files (.rdlc) directly to the Response stream without preview(转)
    dedecms 5.7后台拿WEBSHELL
    sql注入语句大全
    常用putty命令汇总
    sql学习笔记(要够长)
    Ubuntu自动运行脚本
    backtrack安装优化过程
    原创【bt5非官网版本】 在虚拟机下无法连接网络的解决方案
    第五章——循环结构5.1
    Kali Linux 1.0
  • 原文地址:https://www.cnblogs.com/JimmyBright/p/4637090.html
Copyright © 2020-2023  润新知