I have the following code. It works to the extent where the first packet is sent but once it gets inside the while loop the value is changed to -1 and therefore dosnt loop that piece of code once the loop is completed once. Im trying to put 512 bytes of data into a packet at a time and then send it across the network but this isnt working due to the above. I'd be greatful if someone could point out what I'm doing wrong and possibly suggest a fix.
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 class
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;