0

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;
DMo
  • 591
  • 2
  • 6
  • 13
  • Reading up on this I think I need to use a channel for the file and ByteBuffer? – DMo May 22 '12 at 18:04

1 Answers1

0

Well, it looks like your file has only 512 bytes of data, because -1 is returned when end of file is reached, as stated here: http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read(byte[], int, int)

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48