从套接字读取文件的正确方法是什么?(What is the correct way of reading files in from the socket?)

编程入门 行业动态 更新时间:2024-10-18 18:29:23
从套接字读取文件的正确方法是什么?(What is the correct way of reading files in from the socket?)

什么是从套接字读取文件的正确方法? 因为即使在客户端写入文件已经完成,读取文件的循环也不会结束。 如果我仍然要读取数据,我甚至尝试打印缓冲区位置和长度。

这是我读取文件的代码。

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.

更多推荐

本文发布于:2023-04-28 06:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   文件   方法   correct   files

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!