简体   繁体   English

如何“清除”Java DatagramSocket上的接收缓冲区?

[英]How to “clear out” the receive buffer on a Java DatagramSocket?

I have a Java program that is constantly being sent UDP data from an external system. 我有一个Java程序,不断从外部系统发送UDP数据。

Periodically, we need to stop receiving data (because another machine is handling it). 我们需要定期停止接收数据(因为另一台机器正在处理它)。 During those times, my socket reader thread goes into a sleep loop. 在那段时间里,我的套接字读取器线程进入睡眠循环。 When it is time to start receiving packets, I go into socket.receive(Packet) again and have a buffer full of packets that I should not be handling. 当开始接收数据包的时候,我再次进入socket.receive(Packet) ,并且有一个我应该处理的数据包缓冲区。 (The data came while in the "stop time".) (数据来自“停止时间”。)

Is there a way to clear the buffer of a DatagramSocket? 有没有办法清除DatagramSocket的缓冲区?

If not, what is the best alternative? 如果没有,最好的选择是什么? Set the buffer size to 0 when I go into the wait state and bring it back when I start to service packets again? 当我进入等待状态时将缓冲区大小设置为0,并在我再次开始服务数据包时将其恢复? Close the socket when I while I wait and open a new one when I come back? 当我等待并在我回来时打开一个新的时候关闭插座?

Rather than having the downtime on the socket, have the downtime on whatever code processes the packets. 而不是在套接字上停机,无论代码处理什么代码都会有停机时间。

So the socket continues to receive like it normally would, but if it's on downtime, it just immediately drops the packet. 因此套接字继续像往常一样接收,但如果它处于停机状态,它只会立即丢弃数据包。

Not exactly the most efficient solution, but it's really easy to implement and might be useful as it leaves the node open in other cases for accepting different types of packets at different times. 这不是最有效的解决方案,但它实际上很容易实现,并且可能很有用,因为它在其他情况下打开节点以便在不同时间接受不同类型的数据包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM