关于netty的多个handler链式模式

本文介绍了Netty中handler的链式处理模式,包括服务端引导类、多个inbound和outbound handler的配置。强调了ChannelInboundHandler之间通过ctx.fireChannelRead(msg)传递,而ctx.write(msg)配合flush()用于数据写出。同时指出ChannelOutboundHandler应注册在最后一个ChannelInboundHandler之前。
摘要由CSDN通过智能技术生成

1. 老规矩, 引入我们喜闻乐见的maven依赖

1 <dependency>
2     <groupId>io.netty</groupId>
3     <artifactId>netty-all</artifactId>
4     <version>4.1.6.Final</version>
5 </dependency>

2. 服务端

  2.1: 服务端引导类:

 1 public class EchoServer {
 2 
 3     private int port;
 4 
 5     private EchoServer(int port) {
 6         this.port = port;
 7     }
 8 
 9     private void start() throws Exception {
10         System.out.println("Echo Server Start");
11         EventLoopGroup group = new NioEventLoopGroup();
12         try {
13             ServerBootstrap b = new ServerBootstrap();
14             b.group(group)
15                     .channel(NioServerSocketChannel.class)
16                     .localAddress(new InetSocketAddress(port))
17                     .childHandler(new ChannelInitializer<SocketChannel>() {
18                         @Override
19                         public void initChannel(SocketChannel ch) throws Exception {
20                             ch.pipeline().addLast(new EchoOutboundHandler1());
21                             ch.pipeline().addLast(new EchoOutboundHandler2());
22                             
23                             ch.pipeline().addLast(new EchoInboundHandler1());
24                             ch.pipeline().addLast(new EchoInboundHandler2());
25                         }
26                     });
27             ChannelFuture f = b.bind().sync();
28             System.out.println("Server Start Listen At: " + port);
29             f.channel().closeFuture().sync();
30         } finally {
31             group.shutdownGracefully();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值