question

KanWang-4780 avatar image
0 Votes"
KanWang-4780 asked cheong00 answered

Unable to listen UDP port in C#

I am trying to listen UDP port 10086, store the data in the string "loggingEvent", combine the string and send it to the UDP port 51999. The Udpclient 10086 is used to listen port 10086 and the Udpclient 10087 is for sending the message to port 51999.

Although I am able to receive data in the UDP tool "Packet Sender"97781-packet-sender.jpg, the C# code failed to listen to the message on port 10086. However, the port "10086", "10087" and "51999" really works, which can been found by using the command "net-stat -ano".97708-netstat-ano.jpg After debugging, I found that the thread exited at the line "var udpResult = await udpClient_listen.ReceiveAsync();", which confused me a lot. I have also tried non-asynchronous and still does not work. However, the "SendAsync" function works well.

In "CharacteristicPage.xaml.cs"


    public static string udp_listener_ip;
    public static int udp_listener_port;
    public static int udp_client_port;
    public static string udp_message;
    public static UdpClient udpClient_listen;
    public static UdpClient udpClient_send;
    public static string loggingEvent; 
     
    private void button_udp_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
         IPEndPoint endPoint_listen= new IPEndPoint(IPAddress.Parse(udp_listener_ip), 10086);
         udpClient_listen = new UdpClient(endPoint_listen);
    
         IPEndPoint endPoint1 = new IPEndPoint(IPAddress.Parse(udp_listener_ip), 10087);
         udpClient_send = new UdpClient(endPoint1);
    
         UDPListener();
     }
    
     private static async Task UDPListener()
     {
         try
         {
             while (true)
             {
                 Debug.WriteLine("###############UDP listener task start###############");                   
                 var udpResult = await udpClient_listen.ReceiveAsync();
                 loggingEvent = Encoding.ASCII.GetString(udpResult.Buffer);
                 Debug.WriteLine("UDP listener received: " + loggingEvent);
             }
         }
    
         catch (Exception e)
         {
             Debug.WriteLine(e.Message);
             var messageDialog = new MessageDialog(e.Message, "UDP connect failures");
             await messageDialog.ShowAsync();
         }
     }




In "ObservableGattCharacteristic.cs"


 private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
     {
         await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
             Windows.UI.Core.CoreDispatcherPriority.Normal,
             () =>
         {
             SetValue(args.CharacteristicValue);
         });
           
         var udpClient_send = Views.CharacteristicPage.udpClient_send;
         var loggingEvent = Views.CharacteristicPage.loggingEvent;
    
         try
         {
             IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(Views.CharacteristicPage.udp_listener_ip), 51999);
    
             DateTime foo = DateTime.Now;
             long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();
    
             byte[] Payload = Encoding.UTF8.GetBytes(unixTime.ToString() + "," + loggingEvent + "," + ParseValue(value));
    
             await udpClient_send.SendAsync(Payload, Payload.Length, endPoint);
             Debug.WriteLine("UDP send message: " + Encoding.UTF8.GetString(Payload));
         }
    
         catch
         {
             Debug.WriteLine("FAILED to publish message!" );
         }
     }


dotnet-csharpwindows-forms
packet-sender.jpg (156.9 KiB)
netstat-ano.jpg (187.1 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DanielZhang-MSFT avatar image
0 Votes"
DanielZhang-MSFT answered KanWang-4780 commented

Hi KanWang-4780,
Please use wait method to wait for your UDPListener task to complete execution.

 private void button_udp_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
 {
      ....
      UDPListener().Wait();
  }

Best Regards,
Daniel Zhang


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

98077-debug1.jpg98095-debug2.jpg




Hi Daniel,

I have tried the "Wait()" function and the same problem happened. After running "var udpResult = await udpClient_listen.ReceiveAsync();", the program will exit the debug mode and fail to extract message from port 10086.

Best regards,
Asher

0 Votes 0 ·
debug1.jpg (395.1 KiB)
debug2.jpg (399.0 KiB)

Hi @KanWang-4780,
Please try to use the same UdpClient for both sending and receiving.
Best Regards,
Daniel Zhang

0 Votes 0 ·

Hi DanieI,

I have tried the same UdpClient "10086" for both sending and receiving at the very start which does not work. Then I tried different UdpClients and still does not work.

Best wishes,
Asher

0 Votes 0 ·

Add udpClient_listen.Wait() as the first line in while(true) loop. You have to wait until there is new incoming UDP packet to receive it.

0 Votes 0 ·

Sorry, it shows that "UdpClient" does not contain a definition for "Wait()"; while, I have already use the "await udpClient_listen.ReceiveAsync();" to wait until there is new incoming UDP packet to receive it

0 Votes 0 ·
cheong00 avatar image
0 Votes"
cheong00 answered

Here's something I wrote long time ago and revised a bit using ReceiveAsync(), your code looks okay from me.

         static async System.Threading.Tasks.Task Main(string[] args)
         {
             Console.WriteLine("Press Ctrl-C to stop.");
             System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(UdpSendTest));
             t.Start();
             await UdpRecvTest();
         }
    
         static void UdpSendTest()
         {
             System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient();
             byte[] buffer = System.Text.Encoding.Default.GetBytes("Hello");
             Random r = new Random();
             System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), r.Next(10000) + 10000);
    
             while (true)
             {
                 udpClient.Send(buffer, buffer.Length, ep);
                 ep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), r.Next(10000) + 10000);
             }
         }
    
         static async System.Threading.Tasks.Task UdpRecvTest()
         {
             try
             {
                 System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 0);
                 Console.Write("Begin receiving... ");
                 System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(11000);
                 while (true)
                 {
                     System.Net.Sockets.UdpReceiveResult result = await udpClient.ReceiveAsync();
                     Console.WriteLine(System.Text.Encoding.Default.GetString(result.Buffer));
                 }
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.ToString());
             }
         }


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.