Rob Ojeda
Rob Ojeda

Reputation: 23

Netty: How to handle received chunks from a ChunkedFile

I am new to netty and I am attempting to transfer a chunkedfile from a server to a client. Sending the chunks work just fine. The problem is on how to handle the received chunks and write them to a file. Both methods that I tried give me a direct buffer error.

Any help would be greatly appreciated.

Thanks!

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

         System.out.println(in.toString());


         //METHOD 1: write to file
         FileOutputStream fos = new FileOutputStream("c:\\test.txt");
         fos.write(in.array());


         //METHOD 2: getting desperate   
         //InputStream inputStream = new ByteBufInputStream(in); 
         //ChunkedStream chkStream = new ChunkedStream(inputStream);             
         //outputStream.write( (chkStream.readChunk(ctx).readBytes(in, 0)).array());

         //if(chkStream.isEndOfInput()){
         //  outputStream.close();
         //  inputStream.close();
         //  chkStream.close();
         //}


         return;

     }

     out.add(in.toString(charset));

}

Upvotes: 2

Views: 2496

Answers (2)

sos418
sos418

Reputation: 852

I use netty 4.1 version to receive chunks and write to file.

  1. use ByteBuf to receive the ChunkFile or FileRegion and convert it to ByteBuffer which is java nio.
  2. Get the FileChannel of RandomAccessFile and write ByteBuffer in.

Below is my handler code:

public class FileClientHandler extends ChannelInboundHandlerAdapter {

@Override
protected void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {

    File file = new File(dest);//remember to change dest

    if (!file.exists()) {
        file.createNewFile();
    }

    ByteBuf byteBuf = (ByteBuf) msg;
    ByteBuffer byteBuffer = byteBuf.nioBuffer();
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    FileChannel fileChannel = randomAccessFile.getChannel();

    while (byteBuffer.hasRemaining()){;
        fileChannel.position(file.length());
        fileChannel.write(byteBuffer);
    }

    byteBuf.release();
    fileChannel.close();
    randomAccessFile.close();

}}

Upvotes: 2

Norman Maurer
Norman Maurer

Reputation: 23557

Use a FileChannel:

ByteBuf in = ...;
ByteBuffer nioBuffer = in.nioBuffer();
FileOutputStream fos = new FileOutputStream("c:\\test.txt");
FileChannel channel = fos.getChannel();
while (nioBuffer.hasRemaining()) {
    channel.write(nioBuffer);
}
channel.close();
fos.close();

Upvotes: 2

Related Questions