netty4.x Chinese Course series (vi) from the beginning bootstrap

Source: Internet
Author: User

netty4.x Chinese Course series (vi) from the beginning bootstrap

In fact, since the Chinese Course series (v) have not known what they think. Coupled with the busy work there are some problems. I wanted to give up maintenance so much. Did not expect to have a friend and I said Baidu search recommended my article. A little bit excited in a moment. Decide that you want to complete this tutorial series. Here sincerely want to support my friends to apologize. Really let you down. I have this kind of insane idea that I want to give up. Never again.

In fact, along with the gradual in-depth study of Netty. I feel that I still have a lack of understanding of Netty. Add the author Chinese class is the art teacher teaches. So.. Say more is all tears. ~~o (>_<) o ~ ~

The following begins the text:

An overview of the package structure of the Netty framework is not difficult to see. In fact, Netty is composed of five major modules.

    1. Bootstrap is responsible for booting the boot
    2. Buffer is Netty's own encapsulated cache
    3. Channel is responsible for managing and establishing connections
    4. Handler is the processor in the responsibility link pattern
    5. Util are some of the tools that Netty provides and uses
How to start the Netty server

Netty Startup server-related classes are all in the bootstrap package. So in this chapter we start from the beginning, starting with the contents of the bootstrap package. Start by creating a Netty server for everyone to step through the Netty application.

Compared to the fifth chapter of the Channelhandler inside the codec bootstrap inside can be said to be less content of the poor. Take a look at the contents of his package:

Simple three classes, one interface.

Bootstrap is the initiator class for the client.

Serverbootstrap is the startup program class for the server

Bootstrap and Serverbootstrap inherit abstractbootstrap.

ChannelFactory is the interface used to create the channel in Abstractbootstrap

The following code takes the start-up program of the server as an example:

Step One: Instantiate Serverbootstrap

First of all we need to instantiate a Serverbootstrap server boot loader. Such as:

Step two: Set up its thread group

Create two Nioeventloopgroup, one for the parent thread (Boss thread) and one for the child thread (work thread).

Set the thread group for bootstrap

The main purpose of setting up a thread group is to handle events and IO operations in the channel.

The source code for the Serverbootstrap group method:

The parent thread group is passed to the parent class. The detailed explanation is in the last side. Involved too much of something. At the back of the explanation.

Step three: Set the channel type

To set the channel type:

Source code for Channel () method in Serverbootstrap:

We can see that a channel factory has been created and set up.

is the source of bootstrapchannelfactory. It is a static class of the final state. Implement ChannelFactory. The function is to create and return a new channel based on the type of channel initially set.

Step four: Set up the responsibility link

The responsibility chain model is the core part of Netty. Each processor is responsible for only his own things. The processing results are then passed down according to the chain of responsibility.

We are going to set up a responsibility link in the initial. It is set when a channel is initialized after it is created. Serverbootstrap is the source code for the Init () method:

Create a channel in which to initialize the processor inside the Setup pipeline.

Step five: Bind and listen to the port

Binds and sets the listening port.

After the 5 steps above, our server is enough to start up. Many of the settings are Netty by default. What do we do if we want to set our own parameters? Netty provides this method.

Step Six: Other Settings

1. Set channel option configuration:

In previous versions of Netty, they were configured as strings. After the release of the 4.x version, it was uniformly modified to use the Channeloption class to implement the configuration.

For example:

Whether the connection is saved by the socket connection:

There are a number of other parameters. As shown in the following:

This is not a detailed lecture. Reference: Io.netty.channel.ChannelOption

2. Set the properties of the sub-channel:

Sets the properties of the child channel. A value of NULL is a property that will be deleted.

Explanation Eventloopgroup

This explains the role of the two identical thread groups we created above.

The Netty architecture uses a very complex master-slave reactor threading model. To put it simply, it is. The parent thread group (Parentbosser in the Code) acts as a (acceptor) role. is responsible for receiving the client's connection request, processing the completion request, creating a channel and registering it with a thread in the child thread group (Childworker in the code), and then this thread will be responsible for the channel read and write, codec and other operations.

Source Code View:

In step four we set up the responsibility link. Here is the channel initialization and registration. In this case, Init is the channel initialization. After initialization is complete. Group () is the set parent thread group that gets the step in one of the steps and registers the new channel in.

Is the Initandregister method of Abstractbootstrap.

Method Init () is implemented in Serverbootstrap. The code is as follows:

See the following code is not a kind of and familiar feeling? That's right. Is the piece of code that sets up the responsibility link in step four. This will register the newly created channel to the child thread Group

Ps: Finish ... O (∩_∩) o haha ~ ... Write a good hard to say ... Attach my test sample code. Tired.. Write so many words. Hope to help everyone

1 ImportIo.netty.bootstrap.ServerBootstrap;2 ImportIo.netty.channel.*;3 ImportIo.netty.channel.nio.NioEventLoopGroup;4 ImportIo.netty.channel.socket.nio.NioServerSocketChannel;5 ImportIo.netty.channel.socket.nio.NioSocketChannel;6 ImportIo.netty.handler.codec.LengthFieldBasedFrameDecoder;7 ImportIo.netty.handler.codec.LengthFieldPrepender;8 9 /**Ten * Test: O (∩_∩) o haha ~ One * Created by Tinyz on 2014/8/12. A  */ -  Public classMaintest { -  the      Public Static voidMain (string[] args)throwsException { -  -Nioeventloopgroup Parentbosser =NewNioeventloopgroup (); -Nioeventloopgroup Childworker =NewNioeventloopgroup (); +  -Serverbootstrap bootstrap =Newserverbootstrap (); + Bootstrap.group (Parentbosser, childworker); ABootstrap.channel (Nioserversocketchannel.class); atBootstrap.childhandler (NewChannelinitializer<niosocketchannel>() { - @Override -             protected voidInitchannel (Niosocketchannel ch)throwsException { -Channelpipeline CP =ch.pipeline (); -                 //Length-based decoder -Cp.addlast ("Framer",NewLengthfieldbasedframedecoder (Integer.max_value, 0, 2, 0, 2)); inCp.addlast ("Prepender",NewLengthfieldprepender (4)); -                 // toCp.addlast ("Handler",NewSimplechannelinboundhandler<object>() { +  - @Override the                     protected voidChannelRead0 (Channelhandlercontext ctx, Object msg)throwsException { *  $ System.out.println ();Panax Notoginseng Ctx.channel (). Writeandflush (msg); -  the                     } +                 }); A             } the         }); +Bootstrap.option (Channeloption.so_keepalive,true); -         //bootstrap.childattr () $         Try { $             //binding and listening on ports -Channelfuture future = Bootstrap.bind (9002). sync (); -             //wait for Shutdown event the Future.channel (). Closefuture (). sync (); -}finally {Wuyi             //Freeing Resources the parentbosser.shutdowngracefully (); - childworker.shutdowngracefully (); Wu         } -     } About}
View Code

-------------------------------------------------------------- Split Line -- make a small advertisement -----------------------------------------------------------

Female Ornament Shop : http://aoleitaisen.taobao.com

Welcome Reprint , reproduced must be retained My e-mail: [email protected] Blog address: http://www.cnblogs.com/zou90512 otherwise As infringement

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.