[UWP] 在Windows Phone 10 or Win10 中透過 UDP 接收資料

2015-09-02

這寫法在目前Window 10 IoT 10.0.10240.16384 上面測試過是正常的,然後再Window Phone 10 目前上面測試也是正常的
目前範例 按下按鈕後,會打開Port 1947 ,透過UDP接收資訊,收到後會用Dialog 跳出來..

wp_ss_20150902_0008
C# code:


private async  void btnSend_Click(object sender, RoutedEventArgs e)
 {
 
     try
     {
         //判斷如果重複開啟 就是直接提醒
         if (CoreApplication.Properties.ContainsKey("listener"))
         {
        
             await new MessageDialog("您已經開啟接收端了,不用重複開啟").ShowAsync();
             return;
         }
 
        
         //接收到之後
         datagramSocket.MessageReceived +=
            async delegate(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
             {
                 try
                 {
                     //  throw  new Exception();
                     var reader = args.GetDataReader();
                     reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
 
                     string msg = reader.ReadString(reader.UnconsumedBufferLength);
                     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                     {
                         //收到後顯示
                         // args.RemoteAddress 可發送端的IP資訊
                         new MessageDialog("收到:" +args.RemoteAddress + " 。內容: " + msg).ShowAsync();
 
                     });
                 }
                 catch (Exception ex)
                 {
                     await new MessageDialog("錯誤:" + ex.Message).ShowAsync();
                 }
             };
 
         CoreApplication.Properties.Add("listener", datagramSocket);
 
         //打開1947 port 
         await datagramSocket.BindServiceNameAsync("1947");
 
         await new MessageDialog("成功開啟 Port 1947").ShowAsync();
 
     }
     catch (Exception ex)
     {
         await new MessageDialog("錯誤:"+ex.Message).ShowAsync();
     }
 
  
 }

結果:
開啟後
wp_ss_20150902_0006
收到後
wp_ss_20150902_0008

測試方式可以透過 我之前寫的winform 程式測試 :[Winform] 筆記一下,C#透過UDP 傳送資料
參考文件:
https://msdn.microsoft.com/zh-tw/library/windows/apps/windows.networking.sockets.datagramsocket
http://no2don.blogspot.com/2015/08/winform-cudp.html 
https://msdn.microsoft.com/zh-tw/library/windows/apps/br212061.aspx


當麻許的超技八 2014 | Donma Hsu Design.