Netty:如何处理从ChunkedFile接收到的块
我是netty的新手,正在尝试将chunkedfile从服务器传输到客户端。发送块很好。问题在于如何处理接收到的块并将其写入文件。我尝试的两种方法都给了我一个直接的缓冲区错误 任何帮助都将不胜感激 谢谢Netty:如何处理从ChunkedFile接收到的块,netty,file-transfer,chunks,Netty,File Transfer,Chunks,我是netty的新手,正在尝试将chunkedfile从服务器传输到客户端。发送块很好。问题在于如何处理接收到的块并将其写入文件。我尝试的两种方法都给了我一个直接的缓冲区错误 任何帮助都将不胜感激 谢谢 @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { System.out.println(in.to
@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();
我使用Netty4.1版本来接收块并写入文件 使用ByteBuf接收ChunkFile或FileRegion,并将其转换为ByteBuffer,即java nio。 获取RandomAccessFile的文件通道并写入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();
}}