I am trying to implement a udp image transfer program in java. The sender breaks the image up into 1024 byte packets where the first 2 bytes are a short carrying the sequence number and the 3rd byte is a flag indicating whether the packet is the last one or not.
When I execute the receiver and send the image using the sender the transferred image is incomplete and has strange colours on it. Other times when I execute the receiver, it will stick after sending several hundred packets.
Here is the code for the receiver which takes the received packets and writes it to a byte stream.
double DATAGRAM_MAX_SIZE = 1024;
byte[] recieveData = new byte[(int) DATAGRAM_MAX_SIZE];
ByteArrayInputStream bais = new ByteArrayInputStream(recieveData);
DataInputStream dis = new DataInputStream(bais);
// Loop until all packets received
byte isLast = 0;
while(true) {
receievePacket = new DatagramPacket(recieveData, recieveData.length);
try {
receieveSocket.receive(receievePacket);
} catch (IOException e) {
System.out.println("Error receieving packet");
e.printStackTrace();
}
Short sequenceNum = dis.readShort();
isLast = dis.readByte();
System.out.println(recieveData[0] + " " + recieveData[1] +" " + recieveData[2]);
if (!seenSeq.contains(sequenceNum)) {
seenSeq.add(sequenceNum);
bos.write(recieveData, 3, (int) DATAGRAM_MAX_SIZE-3);
}
dis.reset();
// Terminate loop if last packet received
if (isLast == 1) {
break;
}
}
// Byte array to hold image data from stream
byte[] imageData = bos.toByteArray();
Whenever the receiver does manage to receieve all packets here is the resulting image: