简体   繁体   English

从套接字读取文件的正确方法是什么?

[英]What is the correct way of reading files in from the socket?

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();
    }
}

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. 在这里为阻塞模式套接字提供了一个示例,但是将其调整为NIO并非易事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM