【问题标题】:Netty: How to handle received chunks from a ChunkedFileNetty:如何处理从 ChunkedFile 接收到的块
【发布时间】:2014-09-17 10:32:26
【问题描述】:

我是 netty 的新手,我正在尝试将 chunkedfile 从服务器传输到客户端。发送块工作得很好。问题在于如何处理接收到的块并将它们写入文件。我尝试的两种方法都给我一个直接的缓冲区错误。

任何帮助将不胜感激。

谢谢!

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

}

【问题讨论】:

    标签: netty file-transfer chunks


    【解决方案1】:

    使用文件通道:

    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】:

    我使用 netty 4.1 版本来接收块并写入文件。

    1. 使用 ByteBuf 接收 ChunkFile 或 FileRegion 并将其转换为 ByteBuffer 即 java nio。
    2. 获取RandomAccessFile的FileChannel,写入ByteBuffer。

    下面是我的处理程序代码:

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

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 2020-12-30
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多