L
L
Limit TGL @ Limit2016-12-10 02:19:11
Java
Limit TGL @ Limit, 2016-12-10 02:19:11

What is the correct way to transfer a file through Java NIO?

//Цикл принимающей стороны
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(
                Paths.get(file.getPath()), StandardOpenOption.WRITE);
        while (true) {
            if (offset == fileSize) {
                //конец
            }
            byte[] response = receiveByteArray();
            int bytesRead = offset + response.length >= fileSize ? (int) (fileSize - offset) : response.length;
            fileChannel.write(ByteBuffer.wrap(Arrays.copyOfRange(response, 0, bytesRead)), offset);
            offset += bytesRead;
            System.out.println(server.socket().getRemoteSocketAddress() + " >>> " + bytesRead + " bytes");
        }

    private byte[] receiveByteArray() throws IOException {
        ByteBuffer readBuffer = ByteBuffer.allocate(Constants.BUFFER_SIZE); //size = 1460
        server.read(readBuffer); //label 1
        readBuffer.flip();
        return readBuffer.array();
    }


//Отправление массива байт
private void send(SelectionKey key, byte[] response) throws IOException {
        SocketChannel client = (SocketChannel) key.channel();
        client.write(ByteBuffer.wrap(response));
        client.socket().getOutputStream().flush();
        System.out.println(client.socket().getRemoteSocketAddress().toString() + " <<< " + response.length + " bytes");
    }


The receiving and transmitting parties know the full size of the file. The transmitting side in a loop transmits the file in parts of 1460 bytes, and in the end sends everything. The receiving one, at the moment when the transmitting one has transmitted everything, waits endlessly when reading (label 1). The logs show that not everything came, i.e. some arrays were skipped while reading. Checked on the loopback on 2 machines, the file is about 250 mb. On one problem, it occurs but not always, more often the file can be transferred. It has not yet been possible to transfer to the other one at all. After smoking Google, I added a flash after write, which did not solve the problem.
How to organize such a transfer?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question