Execution order of handler in 7.Netty

Source: Internet
Author: User

execution order of handler in 1.Netty  

Handler in the Netty, undoubtedly occupy a very important position. Handler is similar to the filter in the servlet, which can decode and encode the communication message, intercept the specified message,

Unify the processing of log errors, count requests uniformly, control handler execution or not. In a word, nothing it can't do is what you can't imagine.

  all handler in Netty are implemented from the Channelhandler interface . According to the input and output to divide, divided into Channelinboundhandler, channeloutboundhandler two major categories

Channelinboundhandler the packet from the client to the server processing, generally used to perform decoding, read client data, business processing, etc. channeloutboundhandler

Processing of messages sent from the server to the client, typically used for encoding, sending messages to the client

Multiple handler can be registered in Netty. Channelinboundhandler executed in the order of registration; Channeloutboundhandler in reverse order

As shown, handler are sorted according to the order of registration, and the order in which the request enters Netty is:

example of handler execution sequence code in 2.Netty:

Client code Ibid.

Service-side code and business logic classes:

ImportIo.netty.bootstrap.ServerBootstrap;ImportIo.netty.channel.Channel;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelInitializer;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.nio.NioServerSocketChannel;/*** Configure server functions, such as threads, ports? Implements a server handler that contains business logic that determines what to do when a request connects or receives data*/ Public classEchoserver {Private Final intPort;  PublicEchoserver (intPort) {         This. Port =Port; }     Public voidStart ()throwsException {eventloopgroup eventloopgroup=NULL; Try {            //Server-side boot classServerbootstrap Serverbootstrap =NewServerbootstrap (); //connection pooling processing dataEventloopgroup =NewNioeventloopgroup (); Serverbootstrap.group (Eventloopgroup). Channel (Nioserversocketchannel.class)//Specifies the channel type Nioserversocketchannel, an asynchronous mode with Oio blocking mode of Oioserversocketchannel. localaddress ("localhost", port)//set Inetsocketaddress to let the server listen to a port that is waiting for a client connection. . Childhandler (NewChannelinitializer<channel> () {//set Childhandler to perform all connection requests@Overrideprotected voidInitchannel (Channel ch)throwsException {//Register two Inboundhandler, the order of execution is register order, so should be InboundHandler1 InboundHandler2                    ch.pipeline (). AddLast (New EchoOutHandler1 ()); ch.pipeline (). AddLast (                     NewEchoOutHandler2 ());                     //Register two Outboundhandler, the order of execution is in reverse order of registration, so it should be OutboundHandler2 OutboundHandler1                   ch.pipeline (). AddLast (New EchoInHandler1 ()); ch.pipeline (). AddLast (                     New EchoInHandler2 ());            }                    }); //Finally, the binding server waits until the binding is complete, the call to the sync () method blocks until the server finishes binding, and the server waits for the channel to close, because sync () is used, so the shutdown operation is also blocked. Channelfuture channelfuture =serverbootstrap.bind (). sync (); System.out.println ("Start listening, the port is:" +Channelfuture.channel (). localaddress ());        Channelfuture.channel (). Closefuture (). sync (); } finally{eventloopgroup.shutdowngracefully (). sync (); }    }     Public Static voidMain (string[] args)throwsException {NewEchoserver (20000). Start (); }}

Business Class EchoInHandler1:

ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelInboundHandlerAdapter;Importjava.util.Date;ImportCn.itcast_03_netty.sendobject.bean.Person; Public classEchoInHandler1extendsChannelinboundhandleradapter {@Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {System.out.println ("In1"); //notification execution Next Inboundhandler ctx.firechannelread (msg);//channelinboundhandler between the passes, by calling  ctx.firechannelread (msg) 
       implementation  } @Override Public voidChannelreadcomplete (Channelhandlercontext ctx)throwsException {ctx.flush ();//data is sent to Socketchannel after refresh} @Override Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {cause.printstacktrace ();    Ctx.close (); }}

Business Class EchoInHandler2:

ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelInboundHandlerAdapter;Importjava.util.Date; Public classEchoInHandler2extendsChannelinboundhandleradapter {@Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {System.out.println ("In2"); Bytebuf buf=(BYTEBUF) msg; byte[] req =New byte[Buf.readablebytes ()];        Buf.readbytes (req); String Body=NewString (req, "UTF-8"); System.out.println ("Receive Client data:" +body); //writing data to clientsSYSTEM.OUT.PRINTLN ("server sends data to client"); String currenttime=NewDate (System.currenttimemillis ()). ToString (); Bytebuf resp=Unpooled.copiedbuffer (Currenttime.getbytes ());    Ctx.write (RESP);//  ctx.write (msg) will be passed to  channeloutboundhandler  } @Override Public voidChannelreadcomplete (Channelhandlercontext ctx)throwsException {ctx.flush ();//data is sent to Socketchannel after refresh} @Override Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {cause.printstacktrace ();    Ctx.close (); }}

Business logic class EchoOutHandler2:

ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelOutboundHandlerAdapter;Importio.netty.channel.ChannelPromise; Public classEchoOutHandler2extendsChanneloutboundhandleradapter {@Override Public voidWrite (Channelhandlercontext ctx, Object msg, Channelpromise Promise)throwsException {System.out.println ("Out2"); //perform the next Outboundhandler            Super. Write (CTX, MSG, promise); }}

Business Logic class EchoOutHandler1:

Importjava.util.Date;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelOutboundHandlerAdapter;Importio.netty.channel.ChannelPromise; Public classEchoOutHandler1extendsChanneloutboundhandleradapter {@Override//send a message to the client     Public voidWrite (Channelhandlercontext ctx, Object msg, Channelpromise Promise)throwsException {System.out.println ("OUT1"); String currenttime=NewDate (System.currenttimemillis ()). ToString (); Bytebuf resp=Unpooled.copiedbuffer (Currenttime.getbytes ());        Ctx.write (RESP); Ctx.flush (); After the Ctx.write () method executes, you need to call the flush () method to make it execute immediately  }}

Operation Result:

Start listening, port:/127.0.0.1:20000in1in2 receive client data: QUERY time Orderserver send data to client OUT2OUT1

Summarize:

In the process of using handler, it is important to note:

  1, the transfer betweenChannelinboundhandler , by calling Ctx.firechannelread (msg) implementation; Call Ctx.write (msg) will be passed to the Channeloutboundhandler

2. After thectx.write () method executes, the flush () method needs to be called to make it execute immediately.

3,Channeloutboundhandler in the registration time needs to be placed before the last Channelinboundhandler , otherwise it will not be delivered to Channeloutboundhandler

(Pipeline pipeline Outhander can not be put to the last, otherwise does not take effect)

4,Handler The consumption processing put in the last processing.

Execution order of handler in 7.Netty

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.