gpt4 book ai didi

java - 读取分块文件 Netty Java

转载 作者:行者123 更新时间:2023-11-30 11:05:59 24 4
gpt4 key购买 nike

我目前正在制作一个学习 netty 的项目,我正在尝试使用 ChunkedFileHandler 将文件从服务器发送到客户端。发送文件的服务器端代码

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("In channel and the context is " + ctx);
ctx.writeAndFlush(new ChunkedFile(new File("Test//ige.dat")));
}

文件在控制台中记录时发送。但是现在回到客户端,我的记录器说我正在接收 1024 字节的大块文件,这绝对没问题。

public class ChunkedFileClientHandler extends SimpleChannelInboundHandler<ChunkedFile> {

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("Read a chunk of file");
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("Chunk read completed!");
}

文件服务器发送的是 239 MB。每次接收到 block 时,首先触发 channelRead 并触发 channelReadComplete。

现在我的问题是如何组装这些 block 并再次形成文件,文件名和所有其他信息都完好无损。我查看了 netty 网站,但他们没有用于读取分块文件的客户端代码。

谢谢

最佳答案

ChunkedFile API 只传输文件的内容。如果您还需要传输文件名和所有其他信息(具体是什么信息?),您需要提出一个协议(protocol),允许您传输文件数据之外的其他信息。

或者,您可以使用现有协议(protocol)(例如 HTTP),它已经包含用于传输文件名及其内容的 header 。

要将数据写入文件,只需创建一个具有目标路径的 FileOutputStream 并将接收到的数据写入其中即可。

关于java - 读取分块文件 Netty Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com