1. Summary of netty Source Code Analysis

Posted by moniphp on Tue, 08 Oct 2019 15:25:08 +0200

As Java programmers, netty should be more or less exposed to everyone. Netty is widely used as an asynchronous event-driven network framework. We can see from a map of netty's official website what features netty has:

netty's core competence has three points:

  • Extensible Event Model
  • Universal Communication API
  • Byte Buffer with Zero Copy Ability

On the basis of these three core competencies, support for a variety of protocols and transport services has been extended.
Of course, the advantages of netty are more than that. Later, we will analyze the advantages of netty through source code. The following article has tacitly accepted that you are familiar with the basic use of netty.

Here's the simplest netty code to create a server (excerpted from netty's official website) https://netty.io/wiki/user-guide-for-4.x.html The next analysis is based on the following code:

EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)
             .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new DiscardServerHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
    
            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)
    
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

The next source analysis is based on netty version 4.1.39.Final.

Topics: Netty Java less network