Netty--nioeventloop drip Work

Source: Internet
Author: User

Netty is a recent project to use the NIO framework, find a variety of information, found that praised it a bit more, so decided to use it: in fact, the second choice, Mina or Netty or write their own. For Mina, also not familiar, but look at various introductions, seemingly netty work is very good, especially the latest 4.x and 5.x reconstruction, and the use of clear understanding of the structure of the first.

The first thing to do is run the app (more on the official website), I'm an example of MQTT:

1M_bossgroup =NewNioeventloopgroup ();2M_workergroup =NewNioeventloopgroup ();3         4Final Nettymqtthandler handler =NewNettymqtthandler ();5 handler.setmessaging (messaging);6 7Serverbootstrap B =Newserverbootstrap ();8 B.group (M_bossgroup, M_workergroup)9. Channel (Nioserversocketchannel.class) Ten. Childhandler (NewChannelinitializer<socketchannel>() {  One @Override A                   Public voidinitchannel (Socketchannel ch) throws Exception { -Channelpipeline pipeline =ch.pipeline (); -                     //Pipeline.addfirst ("Metrics", New Bytesmetricshandler (M_metricscollector)); thePipeline.addfirst ("Idlestatehandler",NewIdlestatehandler (0,0, Constants.default_connect_timeout)); -Pipeline.addafter ("Idlestatehandler","Idleeventhandler",NewMoquetteidletimouthandler ()); -                     //pipeline.addlast ("Logger", New Logginghandler ("Netty", Loglevel.error)); -Pipeline.addlast ("Decoder",NewMqttdecoder ()); +Pipeline.addlast ("Encoder",NewMqttencoder ()); -Pipeline.addlast ("Metrics",NewMessagemetricshandler (M_metricscollector)); +Pipeline.addlast ("Handler", handler); A                  } at              }) -. Option (Channeloption.so_backlog, -) -. Option (CHANNELOPTION.SO_REUSEADDR,true) -. Childoption (Channeloption.so_keepalive,true);  -         Try {     -             //Bind and start to accept incoming connections. inChannelfuture f =B.bind (constants.port); -Log.info ("Server binded"); to F.sync (); +}Catch(Interruptedexception ex) { -Log.error (NULL, ex); the}

In retrospect, how did we write our own serversocket (this is a clumsy instance code):

ServerSocket socket; Channel= Serversocketchannel.open ();//Open channelSocket = Channel.socket ();//get the socket object associated with the pass- throughSocket.bind (NewInetsocketaddress (port));//Set the Scoket on the established port//Configure to use non-blocking mode, in non-blocking mode, you can write a multi-channel program while avoiding the use of complex multithreadingChannel.configureblocking (false);        Channel.register (selector, selectionkey.op_accept); Try {             while(true) {                 This. Selector.select (); Iterator<SelectionKey> iter = This. Selector.selectedkeys (). iterator ();  while(Iter.hasnext ()) {Selectionkey key=Iter.next ();                    Iter.remove ();  This. Handlekey (key); }            }        } Catch(IOException ex) {ex.printstacktrace (); }

The principle is still those, Channel.open (), then register key, then traverse, then do Handlekey () work.

That Netty's writing why so handsome, with this inexplicable doubt, I first regardless of its structure or anything, directly to search, found such an east:

1 Nioeventloop (nioeventloopgroup parent, Threadfactory threadfactory, Selectorprovider selectorprovider) {2         Super(Parent, Threadfactory,false);3         if(Selectorprovider = =NULL) {4             Throw NewNullPointerException ("Selectorprovider");5         }6Provider =Selectorprovider;7selector =openselector ();8}

The 8th line, from the name point of view, a little bit of meaning, look down:

1  Private Selector Openselector () {2         Final Selector Selector; 3         Try {4             selector = Provider.openselector ();

One of the provider is what we are familiar with: the Java.nio.channels.spi.SelectorProvider class.

So this is the work of Selector.open.

Next you can see Nioeventloop:

1     protected voidrun () {2          for (;;) {3Oldwakenup = Wakenup.getandset (false);4             Try {5                 if(Hastasks ()) {6 Selectnow ();7}Else {8Select ();

Continue to look at the Selectedkey handled in this class:

1         FinalNiounsafe unsafe =Ch.unsafe ();2         if(!K.isvalid ()) {3             //Close the channel if the key is not valid anymore4 Unsafe.close (Unsafe.voidpromise ());5             return;6         }7 8         Try {9             intReadyops =k.readyops ();Ten             if(Readyops & (Selectionkey.op_read | selectionkey.op_accept))! = 0 | | Readyops = = 0) { One Unsafe.read (); A                 if(!Ch.isopen ()) { -                     //Connection already closed-no need to handle write. -                     return; the                 } -             } -             if((Readyops & selectionkey.op_write)! = 0) { -                 //Call Forceflush which would also take care of the clear the Op_write once there are nothing left to WRITE + Ch.unsafe (). Forceflush (); -             } +             if((Readyops & selectionkey.op_connect)! = 0) { A                 //Remove Op_connect as otherwise selector.select (..) would always return without blocking at                 // Seehttps://github.com/netty/netty/issues/924 -                 intOPS =k.interestops (); -OPS &= ~Selectionkey.op_connect; - k.interestops (OPS); -  - Unsafe.finishconnect (); in             } -}Catch(cancelledkeyexception e) { to Unsafe.close (Unsafe.voidpromise ()); +         } -     

Now understand, in fact, Netty is also walking such a set of logic.

And then look online, the logic is this:

Nioeventloopgroup extends Multithreadeventexecutorgroup, which initializes a thread pool of n single thread (children = new singlethreadeventexecutor[ Nthreads];)

Each single-threaded object Child[i]=nioeventloop object, and each nioeventloop has a selector field.

The Run method is the specific business logic code that the group needs to work on.

Follow-up plus other class descriptions.

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.