I am testing data transfer using UDP on my computer (localhost). On the sending end, there is a simple while loop that sends packets of 512 bytes. On the receiving end there is a thread that continuously reads form the socket and prints the number of packets it had read so far.
Sending end:
for (int i = 0; i < 5000; i++) {
byte[] data = new byte[512];
try {
client.socket.send(new DatagramPacket(data, 0, data.length, InetAddress.getByName("localhost"), 4337));
} catch (IOException e) {
e.printStackTrace();
}
}
Receiving end:
while (true) {
DatagramPacket packet = new DatagramPacket(input_buffer, input_buffer.length);
try {
socket.receive(packet);
System.out.println("counter = " + l++);
} catch (IOException e) {
e.printStackTrace();
}
}
Output:
...
counter = 1213
counter = 1214
counter = 1215
counter = 1216
counter = 1217
The sender sent 5000 packets, but the receiver received only 1217.
The reason I know the issue lies in the processing speed in the receiving end is that the problem vanishes if I wait a millisecond between sending each packet by adding the line Thread.sleep(1);
Is there any way of solving this problem without adding a delay?