1

What is really the correct way of reading files from the socket? Because the loop on reading the file doesn't end even though on the client side writing the files has been finished. I even tried printing the buffer position and length if I still data to be read.

Here is my code for reading the file.

private void readActualData(SocketChannel socketChannel) {
    RandomAccessFile aFile = null;
    System.out.println("Reading actual Data");
    try {
        aFile = new RandomAccessFile(path, "rw");
        ByteBuffer buffer = ByteBuffer.allocate(50000000);
        FileChannel fileChannel = aFile.getChannel();

        int length;

        while ((length = socketChannel.read(buffer)) >= 0 || buffer.position() > 0) {
            buffer.flip();
            fileChannel.write(buffer);
            buffer.compact();
            System.out.println("Length : "+length+" and Buffer position : "+buffer.position());
        }
        fileChannel.close();
        System.out.println("End of file reached..Done Reading");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
jnapor
  • 63
  • 1
  • 1
  • 9

1 Answers1

3

This code assumes the peer closes the socket when the file has been completely sent. If that isn't the case, you need something a lot more complex, starting by transmitting the file length ahead of the file and then limiting the amount read from the socket to exactly that length. I provided an example for blocking-mode sockets here, but adapting it to NIO is non-trivial.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483
  • I've pondered over what you need to do in the case of multiple files. You have to count down the initial length of the file and when what remains to be read becomes less than `buffer.limit()-buffer.position()` at the end of the read loop you have to adjust the limit of the buffer such that it isn't. – user207421 May 02 '16 at 00:15