我有以下代码。它的工作范围是发送第一个数据包的程度,但是一旦进入while循环,值就会变为-1,因此当循环完成一次后,dosnt循环该段代码。我试图一次将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;
答案 0 :(得分:0)
好吧,看起来你的文件只有512字节的数据,因为在文件结束时会返回-1,如下所述:http://docs.oracle.com/javase/6/docs/api /java/io/FileInputStream.html#read(byte [],int,int)