什么是从套接字读取文件的正确方法? 因为即使在客户端写入文件已经完成,读取文件的循环也不会结束。 如果我仍然要读取数据,我甚至尝试打印缓冲区位置和长度。
这是我读取文件的代码。
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(); } }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(); } }最满意答案
此代码假定对等体在文件完全发送后关闭套接字。 如果不是这种情况,则需要更复杂的东西,首先在文件之前传输文件长度,然后将从套接字读取的数量限制为该长度。 我在这里为阻塞模式套接字提供了一个示例,但是将其调整为NIO并非易事。
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.
更多推荐
发布评论