Netty源码阅读-目录

目录

Posted by ZhaoLe on January 27, 2019

一.Nio相关

二.Netty源码相关

一个netty的服务端的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args) throws InterruptedException {
  EventLoopGroup bossGroup = new NioEventLoopGroup();
  EventLoopGroup wordGroup = new NioEventLoopGroup();
  try {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, wordGroup).channel(NioServerSocketChannel.class)
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ChannelPipeline pipeline = ch.pipeline();
          ...
        }
      });

    ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
    channelFuture.channel().closeFuture().sync();
  } finally {
    bossGroup.shutdownGracefully();
    wordGroup.shutdownGracefully();
  }
}

无论写简单的还是复杂的netty程序,服务端程序都有以下三个步骤:

  1. 定义两个事件循环组,一般来说是NioEventLoopGroup。
  2. 然后使用Netty定义好的服务启动器ServerBootStrap。
  3. 最后在childHandler中定义ChannelInitializer这个类,这个类里面定义的跟我们请求流程有关的handler。

Netty开发基本就是这个模板套路,后面的对源码的理解和分析也是基于这个demo的,会有一些扩展的解读文章会在后续补上。

一.基本构造方法

二.服务端启动

三.EventLoop

四.新连接接入

五.ChannelPipeline

扩展