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