如何最小化 UDP 数据包丢失

2022-01-22 00:00:00 multicast udp java multicastsocket

我每秒接收约 3000 个 UDP 数据包,每个数据包的大小约为 200 字节.我编写了一个 java 应用程序,它监听这些 UDP 数据包并将数据写入文件.然后服务器以先前指定的速率发送 15000 条消息.写入文件后,它仅包含约 3500 条消息.使用wireshark,我确认我的网络接口收到了所有15000条消息.之后我尝试更改套接字的缓冲区大小(最初是 8496 字节):

I am receiving ~3000 UDP packets per second, each of them having a size of ~200bytes. I wrote a java application which listens to those UDP packets and just writes the data to a file. Then the server sends 15000 messages with previously specified rate. After writing to the file it contains only ~3500 messages. Using wireshark I confirmed that all 15000 messages were received by my network interface. After that I tried changing the buffer size of the socket (which was initially 8496bytes):

(java.net.MulticastSocket)socket.setReceiveBufferSize(32*1024);

该更改将保存的消息数量增加到约 8000 条.我不断将缓冲区大小增加到 1MB.之后,保存的消息数量达到了 ~14400.将缓冲区大小增加到更大的值不会增加保存的消息数量.我想我已经达到了允许的最大缓冲区大小.不过,我需要捕获我的网络接口接收到的所有 15000 条消息.

That change increased the number of messages saved to ~8000. I kept increasing the buffer size up to 1MB. After that, number of messages saved reached ~14400. Increasing buffer size to larger values wouldn't increase the number of messages saved. I think I have reached the maximum allowed buffer size. Still, I need to capture all 15000 messages which were received by my network interface.

任何帮助将不胜感激.提前致谢.

Any help would be appreciated. Thanks in advance.

推荐答案

闻起来像一个错误,很可能在您的代码中.如果 UDP 数据包通过网络传递,它们将在本地排队等待传递,正如您在 Wireshark 中看到的那样.也许您的程序在从其套接字读取时没有及时取得进展 - 是否有专门的线程来执行此任务?

Smells like a bug, most likely in your code. If the UDP packets are delivered over the network, they will be queued for delivery locally, as you've seen in Wireshark. Perhaps your program just isn't making timely progress on reading from its socket - is there a dedicated thread for this task?

您可以通过检测哪些数据包被您的程序丢失来取得一些进展.如果所有丢失的数据包都是早期的,那么数据可能在程序等待接收它们之前就已经发送了.如果他们都晚了,也许它退出得太早了.如果它们定期进行,则您的代码中可能会出现一些问题,即循环接收数据包.等等

You might be able to make some headway by detecting which packets are being lost by your program. If all the packets lost are early ones, perhaps the data is being sent before the program is waiting to receive them. If they're all later, perhaps it exits too soon. If they are at regular intervals there may be some trouble in your code which loops receiving packets. etc.

在任何情况下,您似乎都非常担心丢失数据包.按照设计,UDP 不是一种可靠的传输方式.如果这些多播数据包的丢失对您的系统来说是个问题(而不仅仅是出于性能原因您想解决的谜题),那么系统设计就是错误的.

In any case you seem exceptionally anxious about lost packets. By design UDP is not a reliable transport. If the loss of these multicast packets is a problem for your system (rather than just a mystery that you'd like to solve for performance reasons) then the system design is wrong.

相关文章