Unable to listen UDP port in C#

Kan Wang 1 Reputation point
2021-05-19T03:32:34.587+00:00

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!" );  
        }  
    }  
Developer technologies | Windows Forms
Developer technologies | C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,651 Reputation points
    2021-05-19T06:27:43.403+00:00

    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.


  2. cheong00 3,486 Reputation points Volunteer Moderator
    2021-05-20T11:06:10.257+00:00

    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());
                }
            }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.