Netty (twenty-one)-Netty core module 1

One, Bootstrap and ServerBootstrap

1) Bootstrap means booting. A Netty application usually starts with a Bootstrap. The main function is to configure the entire Netty program and connect various components in series. The Bootstrap class in Netty is the startup guide class for the client program, and ServerBootstrap is the server-side startup guide class.

2) Common methods:

  • public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup): This method is used on the server side to set up two EventLoopGroup
  • public B group (EventLoopGroup group): This method is used on the client side to set up an EventLoopGroup
  • public B channel(Class<? extends C> channelClass): This method is used to set a server-side channel implementation
  • public B option(ChannelOption option, T value): used to add configuration to ServerChannel
  • public ServerBootstrap childOption(ChannelOption childOption, T value): used to add configuration to the received channel
  • public B handler(ChannelHandler handler):对应 bossGroup
  • public ServerBootstrap childHandler(ChannelHandler childHandler): This method is used to set the business processing class (custom handler), corresponding to workerGroup
  • public ChannelFuture bind(int inetPort): This method is used on the server side to set the occupied port
  • public ChannelFuture connect(String inetHost, int inetPort): This method is used on the client side to connect to the server

二、Future和ChannelFuture

1) All IO operations in Netty are asynchronous, and it is not immediately known whether the message is processed correctly. But you can wait for it to finish executing or register a listener directly. The specific implementation is through Future and ChannelFuture. They can register a listener. When the operation is executed successfully or fails, the listener will automatically trigger the registered listener event.

2) Common methods:

  • Channel channel(): Returns the channel currently undergoing IO operation
  • ChannelFuture sync(): Wait for the completion of the asynchronous operation

Three, Channel

1), Netty network communication components, can be used to perform network IO operations
2), through the Channel to obtain the current network connection channel status
3), through the Channel to obtain the configuration parameters of the network connection (such as receiving buffer size)
4 ), Channel provides asynchronous network IO operations (such as establishing a connection, reading and writing, and binding ports). Asynchronous calls mean that any IO call will return immediately, and there is no guarantee that the requested IO operation has been completed at the end of the call
5) , The call immediately returns a ChannelFuture instance, by registering the listener to ChannelFuture, you can call back to notify the caller when the IO operation succeeds, fails or cancels.
6) Supports associated IO operations and corresponding handlers
7) Different protocols, different Blocking types of connections have different Channel types corresponding to them, the commonly used Channel types:

  • NioSocketChannel: asynchronous client TCP Socket connection
  • NioServerSocketChannel: Asynchronous server-side TCP Socket connection
  • NioDatagramChannel: Asynchronous UDP connection
  • NioSctpChannel: Asynchronous client Sctp connection
  • NioSctpServerChannel: Asynchronous Sctp server-side connection
    These channels cover UDP and TCP network IO and file IO.

Four, Selector

1) Netty implements IO multiplexing based on the Selector object. One thread through the Selector can monitor multiple connected Channel events.
2) When the Channel is registered to a Selector, the internal mechanism of the Selector can automatically and continuously query (Selector). ) Whether these registered Channels have ready IO events (such as readable, writable, network connection completed, etc.), so that the program can easily use one thread to efficiently manage multiple Channe

Five, ChannelHandler and its implementation class

1) ChannelHandler is an interface that processes IO events or intercepts IO operations and forwards it to the next handler in its ChannelPipeline (business processing chain).
2) ChannelHandler itself does not provide many methods, because this interface has many methods that need to be implemented, and it can be inherited from its subclasses during convenient use.
3) ChannelHandler and its implementation class
ChannelHandler and its implementation class

  • ChannelInboundHandler: used to handle inbound IO events
  • ChannelOutboundHandler: used to handle outbound IO operations
  • ChannelInboundHandlerAdapter: used to handle inbound IO events
  • ChannelOutboundHandlerAdapter: used to handle outbound IO operations
  • ChannelDuplexHandler: used to handle inbound and outbound events

4). We often need to customize a Handler class to inherit ChannelInboundHandlerAdapter, and then implement business logic by rewriting the corresponding method. The corresponding methods are:

public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler {

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelRegistered();
    }
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelUnregistered();
    }

	// 通道就绪事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelActive();
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelInactive();
    }

	// 通道读取数据事件
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.fireChannelRead(msg);
    }

	//读取数据完毕事件
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelReadComplete();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        ctx.fireUserEventTriggered(evt);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelWritabilityChanged();
    }
	
	// 通道发生异常事件
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.fireExceptionCaught(cause);
    }
}

六、Pipeline和ChannelPipeline

1) ChannelPipeline is a collection of Handlers, which is responsible for processing and intercepting inbound or outbound events and operations, which is equivalent to a chain that runs through Netty. (It can also be understood like this: ChannelPipeline is a List of ChannelHandlers that are used to process or intercept Channel inbound events and outbound operations)
2) ChannelPipeline implements an advanced form of interception filter mode, allowing users to fully control events The processing method and how the ChannelHandlers in the Channel interact with each other
3). Each Channel in Netty has and only one ChannelPipeline corresponding to it. Their composition relationship is as follows:
Channel和ChannelPipeline

  1. A Channel contains a ChannelPipeline, and ChannelPipeline maintains a doubly linked list composed of ChannelHandlerContext, and each ChannelHandlerContext is associated with a ChannelHandler
  2. Inbound events and outbound events are in a doubly linked list. The inbound event will be passed from the head of the linked list to the last inbound handler, and the outbound event will be passed forward from the linked list tail to the first outbound handler. Two types of handlers do not interfere with each other

4) Common methods

  • ChannelPipeline addLast(ChannelHandler… handlers): Add a business processing class (handler) to the last position in the linked list
  • ChannelPipeline addFirst(ChannelHandler... handlers): Add a business processing class (handler) to the first position in the linked list

Guess you like

Origin blog.csdn.net/yangxshn/article/details/114155775