Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "clear out" the receive buffer on a Java DatagramSocket?

Tags:

java

sockets

udp

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?

like image 698
Konstantin Tarashchanskiy Avatar asked Oct 10 '22 06:10

Konstantin Tarashchanskiy


1 Answers

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.

like image 50
corsiKa Avatar answered Oct 13 '22 11:10

corsiKa