2
votes

I am currently making a project for learning netty and I am trying to send a file from server to the client using ChunkedFileHandler. Server side code where file is being sent

@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")));
    }

The file is sent as it is being logged in the console. But now coming back on the client side, my logger says I am receiving files in chunks of 1024 bytes which is absolutely fine.

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!");
    }

The file server is sending is of 239 mb. Every time a chunk is received firstly channelRead is fired and the channelReadComplete is fired.

Now my question is how will I assemble these chunks and form the file again with name of the file and every other information intact. I looked at netty website but they don't have client side code for reading chunked file.

Thanks

1

1 Answers

1
votes

The ChunkedFile API transmits only the contents of the file. If you need to also transmit the file name and every other information (what information exactly would that be?), you need to come up with a protocol that will allow you to transmit that other information in addition to the file data.

Alternatively, you can use an existing protocol such as HTTP, which already includes a header for transmitting the name of a file together with its contents.

To write the data to a file, simply create a FileOutputStream with the destination path and write the received data to it.