C# application simply not receiving UDP data

断了今生、忘了曾经 提交于 2020-01-15 12:30:07

问题


I am trying to do something very simple that does not work: With my C# application I simply want to listen for UDP packages on a specific port. With Wireshark I can see very well that the packages that I desire are received perfectly fine (CRC and everything ok).

However, none of the codes I found on internet work. For example this one failes as well:

    private  void ReceiveAsync()
    {

        UdpClient Client = new UdpClient(new IPEndPoint(IPAddress.Any, 51200));

        try
        {
            Client.BeginReceive(new AsyncCallback(OnReceive), null);
        }
        catch (Exception e)
        {
            System.Windows.Forms.MessageBox.Show(e.Message);
        }
    }

    private static void OnReceive(IAsyncResult result)
    {
        System.Windows.Forms.MessageBox.Show("Simply to tell you that something was received on the port");
    }

There are two ethernet network cards installed. Maybe this can be a problem? But even if I specify the IP address specifically it would not change anything.

            UdpClient Client = new UdpClient(new IPEndPoint(IPAddress.Parse("10.0.0.2"), 51200));

I would be very happy about any ideas that could solve this problem. Thank you very much!


回答1:


The code is fine and working - I have tested it.

You need to wait for received data, Client object exist only in ReceiveAsync

Try adding Thread.Sleep(10000)

Edit:
Thread.Sleep(1000) is not good practice since it block the thread.
it's depend on the problem/case that you are trying to solve. you may have some kind of TCP engine that handle multiple connection ,or data processing so you can say data on buffer for some other thread to work on.

If you share the problem that you are trying to solve , maybe can give better answer Also can see the code example from MSDN - UdpClient.BeginReceive




回答2:


I found this thread in here

Receive messages continuously using udpClient

May be this helps.

  1. you should really not show a message box, think about a debug output.
  2. save your input directly after receiving, to avoid blocking the network.


来源:https://stackoverflow.com/questions/16919469/c-sharp-application-simply-not-receiving-udp-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!