我有以下代码。它在发送第一个数据包的范围内起作用,但是一旦它进入while循环,值就会更改为-1,因此一旦循环完成一次,就不会循环该段代码。我试图一次将 512 字节的数据放入一个数据包中,然后通过网络发送,但由于上述原因,这不起作用。如果有人能指出我做错了什么并可能提出修复建议,我将不胜感激。
InetAddress address = packet.getAddress();
int port = packet.getPort();
RRQ RRQ = new RRQ();
int offset = 0;
int length = 512;
int block = 0;
byte[] readBytes = new byte[512];
File file = new File(filename);
FileInputStream is = new FileInputStream(file);
int fileBytes = is.read(readBytes, offset, length);
DatagramPacket outPacket = RRQ.doRRQ(readBytes, block, address, port);
socket.send(outPacket);
System.out.println("Packet sent");
System.out.println(fileBytes);
byte[] outputop = new byte[2];
outputop = outPacket.getData();
System.out.println(outputop[0]);
System.out.println(outputop[1]);
System.out.println("fileBytes = " + fileBytes);
block++;
while (fileBytes != -1){
socket.receive(packet);
fileBytes = is.read(readBytes, offset, length);
System.out.println("fileBytes = " + fileBytes);
outPacket = RRQ.doRRQ(readBytes, block, address, port);
outputop = outPacket.getData();
System.out.println(outputop[0]);
System.out.println(outputop[1]);
socket.send(outPacket);
System.out.println("Packet sent");
block++;
System.out.println(fileBytes);
}
RRQ 类
public DatagramPacket doRRQ(byte[] data, int block, InetAddress address, int port){
int bufferOffset = 4;
int dataOffset = 0;
byte byteBlock = (byte)block++;
byte[] 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){
buffer[bufferOffset] = data[dataOffset];
bufferOffset++;
dataOffset++;
}
return packet;