简体   繁体   中英

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.

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. (The data came while in the "stop time".)

Is there a way to clear the buffer of a 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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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