我试图创建一个TFTP服务器,但是当它收到一个文件时,似乎并非所有文件都保存在服务器上(缺少一些字节)。文件创建正常,大部分数据都被写入,但由于文件不完整,因此被归类为损坏且无法打开。有谁知道如何解决这个问题?
主要班级
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课程
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;
}
}
答案 0 :(得分:1)
这段代码对我来说非常可疑:
byte[] packetData = packet.getData();
byte[] data = new byte[length - 4];
data = Arrays.copyOfRange(packetData, 4, length - 4);
您的输出数组(数据)长度为length - 4
,但您只复制length - 8
个字节。如果packetData中要忽略的字节是前4个字节,那么它应该是
data = Arrays.copyOfRange(packetData, 4, length);
因为最后一个参数不是长度,而是to
索引(不包括)。有关详细信息,请参阅the javadoc。