1. Netty解析:第一个demo——Echo Server

2020-02-12  本文已影响0人  饿了就下楼

EchoClient

    // 创建事件循环组,在client端,创建一个线程组就好了(server端往往配置两个),
    // 主要负责接收IO事件并处理
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // 创建一个启动类实例,方便管理netty的一些组件
        Bootstrap b = new Bootstrap();
        // 让Bootstrap实例知道自己所管理的事件循环组是啥
        b.group(group)
         // 创建了一个可以生成NioSocketChannel类型channel的ChannelFactory实例
         // 并且把它交给Bootstrap实例管理
         .channel(NioSocketChannel.class)
         // 进行一些参数的配置
         .option(ChannelOption.TCP_NODELAY, true)
         // 配置需要的处理器,也是交给了Bootstrap管理
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ChannelPipeline p = ch.pipeline();
                 if (sslCtx != null) {
                     p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                 }
                 //p.addLast(new LoggingHandler(LogLevel.INFO));
                 p.addLast(new EchoClientHandler());
             }
         });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }

  EchoClient记录了Netty的一个客户端完整的使用过程示例。创建了一个Bootstrap实例,它主要负责管理其他的netty组件。并且还创建了一个EventLoopGroup实例,具体为NioEventLoopGroup,它主要负责客户端IO事件的接收和处理。后续执行的groupchannelhandler等方法可以理解为配置了一些netty的组件(其实就是配置到BootStrap中,交由其管理。具体内容见注释)。最后是客户端连接服务端、连接断开后通道关闭、线程组停止工作。

EchoServer

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    final EchoServerHandler serverHandler = new EchoServerHandler();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .option(ChannelOption.SO_BACKLOG, 100)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ChannelPipeline p = ch.pipeline();
                 if (sslCtx != null) {
                     p.addLast(sslCtx.newHandler(ch.alloc()));
                 }
                 //p.addLast(new LoggingHandler(LogLevel.INFO));
                 p.addLast(serverHandler);
             }
         });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

  Server端的逻辑跟Client端有相似之处,不同地方在于 1. server端创建ServerBootstrap来管理server端的netty组件; 2. 创建了两个事件循环组bossGroupworkerGroup,或者有时候把它们分别理解为父子线程组,父线程组主要负责连接操作,而子线程组负责IO事件(例如读写)的接收和处理。3. groupchannel等方法传入的参数与client端不同,还调用了childHandler; 4. 调用了bind负责监听端口等待连接。

Netty是怎么配置BootStrap/ServerBootstrap的

  我们先看看Client端。
  group方法将创建的事件循环组配置到BootStrap中,我们点开BootStrap的group方法看到,它将创建的事件循环组NioEventLoopGroup赋给了BootStrap的父类AbstractBootStrap的group字段。channel方法传入了NioSocketChannel.class,从源代码中可以很容易发现,netty创建了一个BootstrapChannelFactory工厂,他可以用来产生NioSocketChannel实例。

    public B channel(Class<? extends C> channelClass) {
        if (channelClass == null) {
            throw new NullPointerException("channelClass");
        }
        return channelFactory(new BootstrapChannelFactory<C>(channelClass));
    }

channelFactory方法将创建的工厂实例交给AbstractBootStrap的channelFactory字段。option方法主要完成了添加一些配置参数,就是把参数添加到一个map中。handler方法也类似,将一个ChannelInitializer实例赋值给handler字段。进行连接以及后边关闭通道结束线程组等留在后边再讲。
  我们可以看一下BootStrap的父类AbstractBootStrap中有哪些字段,其实会发现,group等方法,实际就是在给这些字段赋值!

AbstractBootStrap的字段

   server端稍有不同,首先ServerBootStrap的group配置了父子事件循环组,可见下方代码的注释。它的channel方法也是生成了ReflectiveChannelFactory,只不过他声称的channel实例是NioServerSocketChannel。handlerchildHandler分别是添加两类处理器,分别对应着父子事件循环组。然后剩余的bind等,留在后面再讲。

    public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) {
        // 将父线程组添加到父类中
       super.group(parentGroup);
       if (childGroup == null) {
            throw new NullPointerException("childGroup");
        }
        if (this.childGroup != null) {
            throw new IllegalStateException("childGroup set already");
        }
        this.childGroup = childGroup;
        return this;
    }

  看完了server和client端的代码,我们可以总结一下:BootStrap和ServerBootStrap的一系列方法(group等)完成的是不断向其进行配置的过程。server端往往会启动两个事件循环组(父子循环组),分别交给ServerBootStrap的父类AbstractBootStrap和ServerBootStrap自己管理,同样的,因为有了父子概念,也可以分别设定handler和childHandler分别交给父类和自己管理,分别对应着父子循环组。channel方法完成了创建channel工厂,只不过对于server和client来说,两者最终创建出来的channel是不同的。最后,server端需要进行bind,而client端需要进行connect
  

*链接

1. Netty解析:第一个demo——Echo Server
2. Netty解析:NioEventLoopGroup事件循环组
3. Netty解析:NioSocketChannel、NioServerSocketChannel的创建及注册
4. Netty解析:Handler、Pipeline大动脉及其在注册过程中体现
5. Netty解析:connect/bind方法背后
6. Netty解析:服务端如何接受连接并后续处理读写事件

上一篇下一篇

猜你喜欢

热点阅读