Writing in the front

Source complex, obscure code, a look at the waste…… How do I start with the source code? This article will take you with the Netty core source code analysis, source code way, after the first master, I hope this article for you in the source code on the study of help.

Audio version address

Netty initialization process analysis

First of all, from the start, if you don’t even use the source code is out of the question. The NettyServer code is listed in the document

  public class NettyServer {

    public static void main(String[] args) {

        // Create two thread groups, bossGroup and workerGroup, with the default number of NioEventLoop children twice the number of CPU cores
        // The bossGroup handles only connection requests. The workerGroup handles the real business with the client
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(0);

        try {
            // The server starts the object
            ServerBootstrap bootstrap = new ServerBootstrap();

            // Chain-programming configuration parameters

            bootstrap.group(bossGroup, workerGroup)
                    // Use NioServerSocketChannel as the server channel implementation
                    // Initialize the server connection queue size. The server processes client connection requests sequentially, so only one client connection can be processed at a time.
                    // When multiple clients arrive at the same time, the server queues the client connection requests that cannot be processed
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // Set the handler for the workerGroup's SocketChannel
                            socketChannel.pipeline().addLast(newMyNettyServerHandler()); }}); System.out.println("netty server start.....");

            // Bind a port and synchronize, generating a ChannelFuture asynchronous object, using isDone() and other methods to determine the execution of asynchronous events
            // Start the server (and bind the port). Bind is an asynchronous operation and sync is to wait for the asynchronous operation to complete
            ChannelFuture cf = bootstrap.bind(9000).sync();

            // Register a listener for cf to listen for events we care about
            /*cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception {if (cf. IsSuccess ()) {system.out.println (" listening on port 9000 succeeded "); } else {system.out.println (" failed to listen on port 9000 "); }}}); * /
            CloseFuture is an asynchronous operation that listens for channel closing
            // Wait until the closing of the channel is completed
            cf.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally{ bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }}}Copy the code

The core code is:

ChannelFuture cf = bootstrap.bind(9000).sync();
Copy the code

What does bootstrap.bind(port) do? Before going into the source code of bootstrap.bind(port), I want to introduce the core classes involved in Netty first, so as to have an overall image, so that I don’t even know which method of which class I am calling when the process tracing. (There is no framework for getting caught up in the flow and it is easy to get lost if the link is too long or involves multiple threads)

Classes you should know before starting the source code process:

AbstractBootstrap is a helper class that makes it easier to build a Channel. The bind() method is useful for stateless connections such as UDP when the ServerBootstrap context is not used

//AbstractBootstrap is a helper class that makes it easy to bootstrap a Channel. It support method-chaining to provide an easy way to configure the AbstractBootstrap.
//When not used in a ServerBootstrap context, the bind() methods are useful for connectionless transports such as datagram (UDP).

abstract class AbstractBootstrap
Copy the code

ServerBootstrap is a subclass of AbstractBootstrap that makes it easier to build ServerChannel server channels

//Bootstrap sub-class which allows easy bootstrap of ServerChannel
class ServerBootstrap
Copy the code

Bootstrap makes it easier to build client channels. The bind() method is better to use in combination with stateless connections. For regular TCP connections, use the connect() method provided

//A Bootstrap that makes it easy to bootstrap a Channel to use for clients.
//The bind() methods are useful in combination with connectionless transports such as datagram (UDP). For regular TCP connections, please use the provided connect() methods.
class Bootstrap
Copy the code

ChannelPipeline is a list of channel handlers that handle or intercept inbound and outbound events. ChannelPipeline implements an advanced form of intercepting filters, giving the user sufficient control over how events are handled and how each ChannelHandler interacts in the pipeline. As for pipeline creation, each channel has its own pipeline and the process of creation is automatic. As for the flow of events in pipeline, interested students can check the official document by themselves as shown in the figure below, which will not be described here

//A list of ChannelHandlers which handles or intercepts inbound events and outbound operations of a Channel. ChannelPipeline implements an advanced form of the Intercepting Filter pattern to give a user full control over how an event is handled and how the ChannelHandlers in a pipeline interact with each other.
//Creation of a pipeline
//Each channel has its own pipeline and it is created automatically when a new //channel is created.
//How an event flows in a pipeline
interface ChannelPipeline
Copy the code

DefaultChannelPipeline the DefaultChannelPipeline implementation, which is usually created by the channel implementation when the channel is created

//The default ChannelPipeline implementation. It is usually created by a Channel implementation when the Channel is created.
class DefaultChannelPipeline
Copy the code

Realizing SingleThreadEventExecutor OrderedEventExecutor interface, it performs the task of all submitted in a single thread.

//Abstract base class for OrderedEventExecutor's that execute all its submitted tasks in a single thread.
abstract class SingleThreadEventExecutor
Copy the code

SingleThreadEventLoop implements the EventLoop interface, which performs all submitted tasks in one thread

//Abstract base class for EventLoops that execute all its submitted tasks in a single thread.
 abstract class SingleThreadEventLoop
Copy the code

NioEventLoop is an implementation of SingleThreadEventLoop, which registers channels with selectors and multiplexes them in the event loop.

//SingleThreadEventLoop implementation which register the Channel's to a Selector and so does the multi-plexing of these  in the event loop.
class NioEventLoop
Copy the code

AbstractChannel Skeleton channel implementation

abstract class AbstractChannel
Copy the code

AbstractNioChannel uses a channel abstract base class implemented based on selector methods.

//Abstract base class for Channel implementations which use a Selector based approach.
class AbstractNioChannel
Copy the code

AbstractNioByteChannel Is a channel that operates on bytes, based on AbstractNioChannel.

//AbstractNioChannel base class for Channels that operate on bytes.
abstract class AbstractNioByteChannel// Its internal classclass NioByteUnsafe extends AbstractNioUnsafe
Copy the code

AbstractNioMessageChannel AbstractNioChannel based, used in operation on the news channel.

//AbstractNioChannel base class for Channels that operate on messages.
abstract class AbstractNioMessageChannel// Its internal classclass NioMessageUnsafe extends AbstractNioUnsafe
Copy the code

NioUnsafe is a subclass of channel. Unsafe that allows the underlying SelectableChannel to be handled.

//Special Channel.Unsafe sub-type which allows to access the underlying SelectableChannel
interface NioUnsafe
Copy the code

AbstractChannelHandlerContext abstract channel process context

class AbstractChannelHandlerContext
Copy the code

To summarize:

Guide:

  • The bootstrap abstract classabstract class AbstractBootstrap
  • The client initiatorclass Bootstrap extends AbstractBootstrap
  • The server bootclass ServerBootstrap extends AbstractBootstrap

Transmission pipeline:

  • Transport pipe interface definitioninterface ChannelPipeline
  • Default transport pipe implementationclass DefaultChannelPipeline

The thread pool

  • Single thread Thread poolclass SingleThreadEventExecutor extends AbstractScheduledEventExecutor implements OrderedEventExecutor
  • Abstract base class for event loopsabstract class SingleThreadEventLoop extends SingleThreadEventExecutor implements EventLoop
  • A multiplexed Nio event loop is implementedclass NioEventLoop extends SingleThreadEventLoop

channel

  • Abstract channel Channel base classabstract class AbstractChannel extends DefaultAttributeMap implements Channel
  • Abstract the Nio channelabstract class AbstractNioChannel extends AbstractChannel
    • public interface NioUnsafe extends Unsafe
  • Abstract Nio byte channelsabstract class AbstractNioByteChannel extends AbstractNioChannel
    • protected abstract class AbstractNioUnsafe extends AbstractUnsafe implements NioUnsafe
    • protected class NioByteUnsafe extends AbstractNioUnsafe
  • Abstract the Nio message channelabstract class AbstractNioMessageChannel extends AbstractNioChannel
    • private final class NioMessageUnsafe extends AbstractNioUnsafe

context

  • Abstract channels handle contextclass AbstractChannelHandlerContext extends DefaultAttributeMap implements ChannelHandlerContext, ResourceLeakHint

The whole thing is broken down into the following parts: the initiator, the transport pipe, the thread pool, the channel, and the context. The bootstrap is used as the master strap to concatenate the entire process. The pipeline concatenates all custom handler logic. Thread pool Netty Custom thread pool processing tasks. Multiplexing event loops. Channel The user reads the transmitted data. Context is used to pass data between multiple handlers, and so on.

Introduction (an appetizer)

The NioEventLoop class provides us with the ability to respond to events and data, event listeners and endless spin. We can get an intuitive understanding through the following drawings.

The corresponding source code is as follows:

  1. First select() times out and blocks waiting for the listener to emit a registered event
  2. ProcessSelectedKeys () handles the event corresponding to the channel that generates the network I/O
  3. RunAllTasks () executes the queue of processing tasks

Write in the last

As the first part of the study of Netty source code, this is the starter phase, which will familiarize you with the composition and responsibilities of the core classes, and give you a general understanding of the overall design. The next article will follow the source code from the main flow. Thanks for seeing this, I hope the text is helpful to you.

I’m dying stranded. I watched a 96-hour movie but didn’t get your “like” or “follow” collection. I think it’s not that you don’t like me enough, but that I didn’t watch the movie long enough…