Netty: How to handle received chunks from a ChunkedFile

无人久伴 提交于 2019-12-14 00:36:32

问题


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));

}

回答1:


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();



回答2:


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();

}}

netty



来源:https://stackoverflow.com/questions/25888260/netty-how-to-handle-received-chunks-from-a-chunkedfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!