0

私は次のコードを持っています。最初のパケットが送信される範囲で機能しますが、whileループ内に入ると、値が-1に変更されるため、ループが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;
4

1 に答える 1

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)

于 2012-05-22T18:55:32.260 に答える