I am implementing a simple java udp socket program. Here are the details:
- Server side: suppose I create 2500 packets in server side, then inform the client that i'm gonna send 2500 packets, and each packet is packetSize bytes. then in a loop, each packet is created and then sent.
- Client side: after being informed of the number of packets, in a for (or while), I wait for 2500 packets to be received.
Here is the problem: The for loop in client side never ends! that means 2500 packets are never received! Although I checked server side and it has sent them all.
I tried setting the socket's receive buffer size to 10 * packetSize using this:
socket.setReceiveBufferSize(10 * packetSize)
but it does not work.
How do you think I could solve this problem? I know UDP is not reliable but both client and server are running on different ports of the same computer!
Here is the code for server side:
for (int i = 0; i < packets; i++) {
byte[] currentPacket = new byte[size];
byte[] seqnum = intToByteArray(i);
currentPacket[0] = seqnum[0];
currentPacket[1] = seqnum[1];
currentPacket[2] = seqnum[2];
currentPacket[3] = seqnum[3];
for (int j = 0; j < size-4; j++) {
currentPacket[j+4] = finFile[i][j];
}
sendPacket = new DatagramPacket(currentPacket, currentPacket.length, receiverIP, receiverPort);
socket.send(sendPacket);
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
and the client side:
int k = 0;
while (true) {
receivedBytes = new byte[size];
receivePacket = new DatagramPacket(receivedBytes, size);
socket.receive(receivePacket);
allBytes.add(receivePacket.getData());
k++;
if (k == packets)
break;
}
allBytes is just a linked list containing received bytes. i use it to reassemble the final file.
P.S. This code works perfect for under 100Mb files. Thanks
DatagramChannelsays something along the lines of: "Data that can not fit in the buffer is silently discarded." Try making sure your buffer size is greater than or equal to the data you're expecting to receive. - Jacob G.DatagramPacketas constructor? - SOFUser