Netty Event monitoring and processing (bottom)

Source: Internet
Author: User
Tags event listener

The previous article introduces the basic concepts of event monitoring, responsibility chain model, Socket interface and IO model, threading model, and the overall structure of Netty, which is one of the three core modules of Netty: Event monitoring and processing.

As mentioned earlier, Netty is a NIO framework that changes the setup, readable, writable, and other state of IO channels, abstracts them into events, passes them in a chain of responsibility, and can insert custom handler on the processing chain to listen and process the events of interest.

Through the introduction, you will learn:

    • Event monitoring and processing model
    • Event Listener: EventLoop
    • Event handling: Channelpipeline and Channelhandler
    • Implementing the WebSocket protocol with Netty
Event monitoring and processing model

For network programming, the general writing process is this:

    • Create the server socket and listen to a port;
    • When there is a client connection, a new client socket is created, which listens to the readable and writable state of the data, and each connection request creates a client socket;
    • Read and write data will invoke the interface provided by the socket, the interface list is mentioned in the previous article;

The traditional model, each client socket creates a separate thread to listen for the socket event, on the one hand, the system can create a limited number of threads, limit the number of concurrent, on the one hand too many threads, thread switching frequently, resulting in a severe performance degradation.

With the development of the operating system IO model, multiplexing IO can be used, one thread listens to multiple sockets, and the server handles client connections, and the client socket listens, which can be processed on different threads.

Netty is the use of Multiplexing IO for event monitoring, in addition, using different threads to handle the client connection, data read and write.

The entire processing structure, as described below, is simple:

    • Boss Eventloopgroup mainly handles the client's connect event, which contains multiple eventloop, each eventloop a thread;
    • Worker Eventloopgroup primarily handles data read, write events for client sockets, including multiple EventLoop, each eventloop a thread;
    • Whether boos or worker, the handling of events is organized by channel Pipleline, which is the realization of the responsibility chain pattern, including one or more handler;
    • Listens on a port, only binds to a eventloop in the Boss Eventloopgroup;
    • Worker Eventloopgroup in a eventloop, can listen to multiple client sockets;

EventLoop

A eventloop is actually bound to a particular thread, and in its lifetime, the bound thread is no longer changed.

EventLoop shoulders two tasks:

    • The first is to perform the IO operations associated with the Channel as an IO thread, including invoking a select wait-ready IO event, reading and writing data and data processing, and so on;
    • The second task is to perform tasks in Taskqueue as a task queue, such as when a user invokes Eventloop.schedule to commit a timed task that is also executed by this thread;

The first task is better understood, the main explanation under the second: from socket data to data processing, to write response data, Netty are processed in a thread, mainly for thread safety considerations, reduce competition and thread switching, through the task queue, the user thread can submit processing logic, Executed in EventLoop.

The whole eventloop thing is to handle the IO event-related logic Runalltask,processio Processio, select, and runalltask the tasks in the task queue, if too many tasks are performed, will affect the processing of IO events, so it will limit the processing time of the task, as follows:

The run code for EventLoop is as follows:

protected void Run () {for (;;)         {Oldwakenup = Wakenup.getandset (false);             try {if (Hastasks ()) {///If there is a task, quickly return Selectnow (); } else {select ();//If there is no task, wait for the event to return if (Wakenup.get ()) {Selector.wakeup                 ();             }} cancelledkeys = 0;             Final Long iostarttime = System.nanotime ();             Needstoselectagain = false;             Handle IO Event if (Selectedkeys! = null) {processselectedkeysoptimized (Selectedkeys.flip ());             } else {Processselectedkeysplain (Selector.selectedkeys ());             }//Calculate IO Processing time final long iotime = System.nanotime ()-iostarttime; Final int ioratio = This.ioratio;             The default is 50//processing the submitted task Runalltasks (Iotime * (100-ioratio)/ioratio);            if (Isshuttingdown ()) {CloseAll ();     if (Confirmshutdown ()) {break;             }}} catch (Throwable t) {try {thread.sleep (1000); } catch (Interruptedexception e) {}}}}
Channelpipeline and Channelhandler

Channelpipeline is an interface that has a default implementation class of Defaultchannelpipeline, with two properties inside it: Head and tail,
Both of these implement the Channelhandler interface, which corresponds to the head and tail of the processing chain.

 protected DefaultChannelPipeline(Channel channel) {     this.channel = ObjectUtil.checkNotNull(channel, "channel");     succeededFuture = new SucceededChannelFuture(channel, null);     voidPromise =  new VoidChannelPromise(channel, true);     tail = new TailContext(this);     head = new HeadContext(this);     head.next = tail;     tail.prev = head;}

When each channel is created, a Channelpipeline object is created to handle the various events of the channel, and the Channelhandler can be dynamically modified dynamically at run time.

Channelhandler the place where the business processing logic is hosted, we touch the most classes, can customize the handler, join the processing chain, and implement the custom logic.

Channelhandler can be divided into two main categories: Channelinboundhandler and Channeloutboundhandle, which correspond to the processing of inbound and outbound messages, corresponding data reads and data writes. It provides an interface method for us to implement and handle various events.

public interface ChannelInboundHandler extends ChannelHandler {    void channelRegistered(ChannelHandlerContext ctx) throws Exception;    void channelUnregistered(ChannelHandlerContext ctx) throws Exception;    void channelActive(ChannelHandlerContext ctx) throws Exception;    void channelInactive(ChannelHandlerContext ctx) throws Exception;    void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception;    void channelReadComplete(ChannelHandlerContext ctx) throws Exception;    void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception;    void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception;}

When customizing handler, Channelinboundhandleradapter or Channeloutboundhandleradapter are generally inherited.

It is important to note that it is not recommended to implement time-consuming or blocking operations directly in Channelhandler, as this may block Netty worker threads, causing Netty to be unable to respond to IO processing in a timely manner.

Implementing the WebSocket Protocol WebSocket protocol using Netty

This is not the focus of this article, simply explained below:

    • is a long-connection protocol, most browsers are supported, through the WebSocket, the server can proactively send messages to the client;
    • WebSocket protocol, the Handshake phase using the HTTP protocol, after the handshake is completed, go websocket own protocol;
    • WebSocket is a binary protocol;
Initialization

Netty provides the Channelinitializer class to facilitate our initialization, create Websocketserverinitializer classes, inherit Channelinitializer classes, and add Channelhandler:

public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {    @Resource    private CustomTextFrameHandler customTextFrameHandler;    @Override    public void initChannel(SocketChannel ch) throws Exception {        ChannelPipeline pipeline = ch.pipeline();        pipeline.addLast("codec-http", new HttpServerCodec());        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));        pipeline.addLast("websocket-protocal-handler",new WebSocketServerProtocolHandler());        pipeline.addLast("custome-handler", customTextFrameHandler);    }}

The analysis of these several handler, are provided by default Netty:

    • Httpservercodec: Used to resolve HTTP requests, mainly in the handshake phase of processing;
    • Httpobjectaggregator: Used to merge the HTTP request header and the request body, mainly in the handshake stage processing;
    • Websocketserverprotocolhandler: Deal with WebSocket protocol;
    • Customtextframehandler: Custom handler for adding your own business logic.

is not very convenient, after websocketserverprotocolhandler processing, read out is the text data, do not have their own processing data package, unpacking problems.

Customtextframehandler

Custom handler for Business processing:

public class CustomTextFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {    @Override    protected void channelRead0(final ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {        final String content = frame.text();        System.out.println("接收到数据:"+content);           // 回复数据        TextWebSocketFrame respFrame = new TextWebSocketFrame("我收到了你的数据");        if (ctx.channel().isWritable()) {              ChannelFuture future = ctx.writeAndFlush(respFrame);          }                     }}

Welcome to scan the QR code below, follow my personal public number ~

Netty Event monitoring and processing (bottom)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.