Netty:如何处理从 ChunkedFile 接收到的块

2024-03-09

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

任何帮助将不胜感激。

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

}

使用文件通道:

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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Netty:如何处理从 ChunkedFile 接收到的块 的相关文章