使用 C# UDP 客户端
我正在制作一个需要始终监听 UDP 数据的程序。
我当前的想法是让此方法在一个线程中不断运行,侦听数据包,然后将它们添加到准备在其他线程中处理的列表中。主要问题是我还想将接收到的 IP 添加到列表中,以便其他线程可以处理它,但我不知道程序是否会暂时停止使用 Receive 方法,是否会丢失处理时接收到的数据包数据或者它是否仍然可以从队列中获取它们。
public void listen()
{
try
{
packetQueue.Add(receivingUdpClient.Receive(ref RemoteIpEndPoint));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
I'm making a program which needs to be listening for UDP Data at all times.
My current idea is have this method running constantly in one thread listening for packets and then adding them to a list ready to be dealt with in other threads. The main problem is I would also like to add the received IP to a list so that the other thread can deal with it but I don't know if the program stops using the Receive method for a moment if it will lose packets received while processing the data or if it can still grab them from a queue.
public void listen()
{
try
{
packetQueue.Add(receivingUdpClient.Receive(ref RemoteIpEndPoint));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
网络流量应该在您的网卡上进行缓冲,这样即使您监听的情况不一致,数据也应该保持一致。至于 IP,您可以从端点获取它,因此您还需要传递它:
如果您想在接收之间错过尽可能少的时间,我建议您使用 BeginReceive 并在处理之前在回调中启动一个新的 BeginReceive回调中接收到的数据。但这会增加一些同步复杂性。
network traffic should be buffered on your network card so the data should be consistent even if you are listening inconsistently. as for the IP you can get it from the endpoint so you'll need to pass that as well:
If you want to miss as little time as possible in between receives I suggest you use BeginReceive and start a new BeginReceive in the callback before processing the received data in the callback. this will add some synchronization complexity though.
我知道没有办法从 Udp 数据包中获取 IP。您需要从端点获取它:
此外,您的程序需要运行非常慢才能开始丢失任何数据包 - 只要您设置了客户端侦听器,Windows 就会为您缓冲这些数据包!
I know of no way to get the IP from the Udp packet. You need to get it form the EndPoint:
Also, your program will need to run VERY SLOWLY to start losing any packets - windows will buffer those for you, so long as you have your client listener set up!