问题
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.
- you should really not show a message box, think about a debug output.
- save your input directly after receiving, to avoid blocking the network.
来源:https://stackoverflow.com/questions/16919469/c-sharp-application-simply-not-receiving-udp-data