diff --git a/netty/service/src/main/java/cn/bunny/service/netty/demo5/PipLineServer.java b/netty/service/src/main/java/cn/bunny/service/netty/demo5/PipLineServer.java new file mode 100644 index 0000000..2e9bf15 --- /dev/null +++ b/netty/service/src/main/java/cn/bunny/service/netty/demo5/PipLineServer.java @@ -0,0 +1,79 @@ +package cn.bunny.service.netty.demo5; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class PipLineServer { + public static void main(String[] args) { + new ServerBootstrap() + .group(new NioEventLoopGroup()) + .channel(NioServerSocketChannel.class) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception { + // 通过 Channel 拿到pipLine + ChannelPipeline pipeline = nioSocketChannel.pipeline(); + // handler 处理结果 + pipeline.addLast("h1", new ChannelInboundHandlerAdapter() { + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + log.info("第一个"); + super.channelRead(ctx, msg); + } + }); + + // handler 第二个处理结果 + pipeline.addLast("h2", new ChannelInboundHandlerAdapter() { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + log.info("第二个"); + super.channelRead(ctx, msg); + } + }); + // handler 第三个处理结果 + pipeline.addLast("h3", new ChannelInboundHandlerAdapter() { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + log.info("第三个"); + super.channelRead(ctx, msg); + nioSocketChannel.writeAndFlush(ctx.alloc().buffer().writeBytes("服务".getBytes())); + } + }); + + // 第四个出栈内容 + pipeline.addLast("h4", new ChannelOutboundHandlerAdapter() { + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + log.info("第四个 出栈"); + super.write(ctx, msg, promise); + } + }); + + // 第五个出栈内容 + pipeline.addLast("h5", new ChannelOutboundHandlerAdapter() { + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + log.info("第五个 出栈"); + super.write(ctx, msg, promise); + } + }); + + // 第六个出栈内容 + pipeline.addLast("h6", new ChannelOutboundHandlerAdapter() { + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + log.info("第六个 出栈"); + super.write(ctx, msg, promise); + } + }); + } + }).bind(8080); + + // 进栈:按照顺序进行 + // 出栈:从后往前走 + } +}