C#应用程序根本不接收UDP数据 [英] C# application simply not receiving UDP data
问题描述
我试图做一些非常简单的事情,但它不起作用:对于我的C#应用程序,我只想在特定端口上侦听UDP包。使用Wireshark,我可以很好地看到我所希望的软件包可以很好地收到(CRC和一切正常)。
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");
}
已安装两个以太网网卡。也许这可能是个问题?但是,即使我明确指定了IP地址,它也不会更改任何内容。
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!
推荐答案
代码很好并且可以正常工作-我已经测试过了。
The code is fine and working - I have tested it.
您需要等待接收到的数据, Client
对象仅存在于 ReceiveAsync
You need to wait for received data, Client
object exist only in ReceiveAsync
尝试添加 Thread.Sleep(10000)
编辑:
Thread.Sleep(1000)
不好,因为它会阻塞线程。
这取决于您要解决的问题/案例。您可能有某种处理多个连接或数据处理的TCP引擎,因此您可以说缓冲区中的数据可供其他线程使用。
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.
如果您共享您尝试解决的问题,也许可以给出更好的答案
也可以从 MSDN-UdpClient.BeginReceive
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
这篇关于C#应用程序根本不接收UDP数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!