下面的代码旨在获取一个 byte[] 和其他一些东西(参见它给出的代码)。然后它构建一个具有一定长度的数据包并返回它。我的问题是当我将文件读入主程序时,我需要数据报包的缓冲区为剩余要发送的字节数(如果小于 512)+ 4。这是为了处理读取请求的最后一个数据包TFTP 服务器。我在“buffer[bufferOffset] = data[dataOffset];”这一行得到一个索引越界异常。谁能帮我理解为什么会发生这种情况以及最好的解决方法是什么?
public DatagramPacket doRRQ(byte[] data, int block, InetAddress address, int port, long fileSize, long sentBytes){
//takes file data and creates a buffer for a DATA packet to be used in a RRQ. This packet
//is passed to MyFirstTFTPServer.java to be modified and sent to client. This is done
int bufferOffset = 3;
int dataOffset = -1;
byte[] buffer = null;
long difference = 0;
int i = 512;
byte byteBlock = (byte)block++;//possible issue with block no increment. test.
if (sentBytes + 512 > fileSize){
difference = fileSize - sentBytes;
difference = difference + 4;
i = (int)difference;
buffer = new byte[i];
} else {
buffer = new byte[516];
}
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
buffer[0] = 0;
buffer[1] = 3;
buffer[2] = 0;
buffer[3] = byteBlock;
for(byte item:data){
bufferOffset++;
dataOffset++;
buffer[bufferOffset] = data[dataOffset];
//System.out.println(bufferOffset);
//System.out.println(dataOffset);
}
return packet;
}