阅读Chunked File Netty Java

时间:2015-04-04 17:30:50

标签: java netty

我目前正在制作一个学习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。每次收到一个块时,首先触发channelRead并触发channelReadComplete。

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

由于

1 个答案:

答案 0 :(得分:1)

ChunkedFile API仅传输文件的内容。如果您还需要传输文件名和其他所有信息(确切地说是什么信息?),您需要提供一个协议,除了文件数据之外,还可以传输其他信息。

或者,您可以使用现有协议,例如HTTP,其中已包含用于传输文件名称及其内容的标头。

要将数据写入文件,只需使用目标路径创建FileOutputStream,然后将接收到的数据写入其中。

相关问题