For my networked Java application, I wrote a thread-safe, non-blocking i/o wrapper over the system-level DatagramSocket. However, I'm confused about something. What happens if a new packet comes in while callback.onDataReceived()
is executing? Is the packet dropped? Is it added to an OS-level queue and "received" on the next iteration of the loop? If so, does that queue have a maximum size?
/*
* Receiving thread
*/
rxThread = new Thread(new Runnable()
{
@Override
public void run()
{
byte[] incomingBuffer = new byte[DataConstants.NUM_BYTES_IN_DATAGRAM_PACKET_BUF];
while (!Thread.currentThread().isInterrupted())
{
DatagramPacket incomingPacket = new DatagramPacket(incomingBuffer, incomingBuffer.length);
try
{
basicSocket.receive(incomingPacket);
callback.onDataReceived(
DatatypeUtil.getNBytes(incomingPacket.getData(), incomingPacket.getLength()),
incomingPacket.getAddress());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
You are correct about the OS level buffering that occurs, you can manipulate the size of the buffers using the API methods DatagramSocket.setRecieveBufferSize() and DatagramSocket.getRecieveBufferSize() .
But
It is also possible to lose some packets as your UDP packets may get dropped if the buffer overflows or if the packets get lost in transit. After all UDP is a connectionless protocol. If you do need to make sure that all your packets are safe and intact you could switch over to TCP.
Coming back to your question, if it so happens that callback.onDataReceived()
takes a little longer to execute, the sender is pumping packets and your UDP buffers get full, then you might start losing packets