I trying to create a TFTP server but when it receives a file it seems that not all of it is saved on to the server (some bytes are missing). The file is created fine and the majority of data is written but as the file is not complete it is classed as corrupt and unopenable. Does anyone know how to fix this issue?
main class
WRQ WRQ = new WRQ();
ACK ACK = new ACK();
DatagramPacket outPacket;
BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));
byte[] bytes;
byte[] fileOut;
outPacket = WRQ.firstPacket(packet);
socket.send(outPacket);
socket.receive(packet);
while (packet.getLength() == 516){
bytes = WRQ.doWRQ(packet);
bufferedOutput.write(bytes);
outPacket = ACK.doACK(packet);
socket.send(outPacket);
socket.receive(packet);
}
bytes = WRQ.doWRQ(packet);
bufferedOutput.write(bytes);
bufferedOutput.close();
outPacket = ACK.doACK(packet);
socket.send(outPacket);
WRQ class
public class WRQ {
public DatagramPacket firstPacket(DatagramPacket packet) throws IOException{
ACK ACK = new ACK();
DatagramPacket ACKpacket = ACK.doACK(packet);
//takes ACK packet and sets block # as 0 to signal that this is the first packet in a WRQ
byte[] ACKcontents = new byte[3];
ACKcontents = ACKpacket.getData();
ACKcontents[2] = 0;
ACKcontents[3] = 0;
ACKpacket.setData(ACKcontents);
return ACKpacket;
}
public byte[] doWRQ(DatagramPacket packet){
int length = packet.getLength();
byte[] packetData = packet.getData();
byte[] data = new byte[length - 4];
data = Arrays.copyOfRange(packetData, 4, length - 4);
return data;
}
}
This code looks very suspicious to me:
Your output array (data) is of length
length - 4
, but you only copylength - 8
bytes to it. If the bytes to ignore in packetData are the first 4 bytes, it should bebecause the last argument is not a length, but the
to
index (exclusive). See the javadoc for details.