public class LineBasedHandlerInitializer extends ChannelInitializer<Channel>{
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
//该LineBasedFrameDecoder将提取的帧转发给下一个ChannelInboundHandler
pipeline.addLast(new LineBasedFrameDecoder(64*1024));
//添加FrameHandler以接收帧
pipeline.addLast(new FrameHandler());
}
public static final class FrameHandler
extends SimpleChannelInboundHandler<ByteBuf>{
@Override
//传入单个帧的内容
protected void channelRead0(ChannelHandlerContext channelHandlerContext,
ByteBuf byteBuf) throws Exception {
// do something with the data extracted from the frame
}
}
}
//创建一个FileInputStream
FileInputStream in = new FileInputStream(file);
FileRegion region = new DefaultFileRegion(
in.getChannel(),0,file.length());
//发送该DefaultFileRegion,并注册一个ChannelFutureListener
channel.writeAndFlush(region).addListener(
new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if (!channelFuture.isSuccess()) {
//处理失败
Throwable cause = channelFuture.cause();
// Do something
}
}
}
);