Discussion on the Netty realization of NIO (3)

Source: Internet
Author: User

1. Preface

The previous chapter, in conjunction with the Java NiO example, explains a basic use of multi-channel IO multiplexing, which is deepened by actual coding. This chapter began to enter the Netty link, the previous two chapters are for Netty to pave the instructions. This section will compare Java's nio example to illustrate a basic design of Netty, which would be very helpful if you had a thorough understanding of the Netty.

International practice, put the basic description of Netty official website: Netty is an asynchronous event-driven network application framework for rapid development of maintainable high-performance protocol servers and clients. Quick and simple does not mean that the application is subject to maintainability and performance issues. Its design is very discreet and uses a variety of protocols, such as FTP, SMTP, HTTP, and various binary and text-based legacy protocols. Netty successfully found a way to achieve development, performance, stability, and flexibility without compromising.

The above description of the main focus on two points: 1. Asynchronous event driver; 2. Multiple protocol parsing. In addition, Netty has high throughput, low latency, less resource waste, and minimal unnecessary memory copy.

2. Example 2.1 Server

    Java in NiO I mentioned 4 elements of the server base: 1. Thread pool; 2. Port; 3.selector;4.channel. Netty is actually the content, but Netty as a well-encapsulated framework, it will not let us get selector, after all, not all IO is this way, the connection process of encapsulation (connect, read, write, disconnect), The other is the protocol resolution that was not mentioned before. We all know that TCP is actually a problem with sticky packets, generally need a protocol to avoid this problem, before also said Netty support a lot of protocols, demo will reflect this.

    public static void Main (string[] args) {Eventloopgroup bossgroup = new Nioeventloopgroup ();        Eventloopgroup Workergroup = new Nioeventloopgroup ();            try {serverbootstrap bootstrap = new Serverbootstrap ();            Bootstrap.group (Bossgroup, Workergroup);            Bootstrap.channel (Nioserversocketchannel.class); Bootstrap.childhandler (New channelinitializer<socketchannel> () {@Override protected V                    OID Initchannel (Socketchannel ch) throws Exception {Channelpipeline pipeline = Ch.pipeline ();                    Pipeline.addlast ("Framer", New Delimiterbasedframedecoder (8192, Delimiters.linedelimiter ()));                    Pipeline.addlast ("Decoder", New Stringdecoder ());                    Pipeline.addlast ("encoder", New Stringencoder ());                     Pipeline.addlast ("Handler", new Simplechannelinboundhandler<string> () {@Override   protected void channelRead0 (Channelhandlercontext ctx, String msg) throws Exception {System                            . OUT.PRINTLN ("===>receive msg:" + msg);                        Ctx.channel (). Writeandflush ("Server get msg:" + msg + "\ r \ n");                }                    });            }            });            Channelfuture future = Bootstrap.bind (7777). sync ();        Future.channel (). Closefuture (). sync ();        } catch (Exception e) {e.printstacktrace ();            } finally {bossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully (); }    }

Eventloopgroup is a thread pool class that Netty is encapsulated two times based on the thread pool framework provided by the JDK. Serverbootstrap is the startup class, which starts with a series of settings: 1. Set the thread pool, 2. Set IO mode (determined by channel); 3. Set handler (handler is a very important encapsulation of Netty, In fact, the only thing we care about IO is the life cycle of the connection, and handler is the one that handles the corresponding business for each life cycle of the connection; 4. Bind the port. This and the Java example is not very similar to the previous part, but the handling of the event does not require the developer's attention, instead of the developer only need to pay attention to the handler to the various stages of processing, depending on the channel type, Netty the processing of IO events is all converted to handler.

Our main concern here is handler, which is a new concept for the past. The above example design a simplest handler, handler take the responsibility chain design pattern, and it is in order, this can not mess. Think about, read the data, read out are binary, the first step of course is to parse the binary, parse out a complete protocol, a lot of parts do not, less to continue to wait for data to come. Delimiterbasedframedecoder is doing this, with a newline character as the agreed protocol. The second step after obtaining the protocol is naturally the parsing protocol, Stringdecoder is the use, that is, we want the client to send a string with a newline character. So what does Stringencoder do? Isn't this code for the protocol? In fact hander manages read processing and also manages write operations, and we also need a protocol to return to the client. So handler is divided into two classes, in and out,in processing the read event, and out handles the write event. The last handler is a custom in type of handler, and after parsing the protocol we do what we need to do here, this is our business layer.

2.2 Client

The client did not use the thread pool before, but Netty still uses the thread pool, because it is not only the socket that needs threading, but also the use of multithreaded technology for business operations that do not need to be executed synchronously. Other local differences are not very big, the specific look at the code.

    public static void Main (string[] args) {Eventloopgroup group = new Nioeventloopgroup ();            try {Bootstrap b = new Bootstrap ();            B.group (group);            B.channel (Niosocketchannel.class); B.handler (New channelinitializer<socketchannel> () {@Override protected void Initchann                    El (Socketchannel ch) throws Exception {Channelpipeline pipeline = Ch.pipeline ();                    Pipeline.addlast ("Framer", New Delimiterbasedframedecoder (8192, Delimiters.linedelimiter ()));                    Pipeline.addlast ("Decoder", New Stringdecoder ());                    Pipeline.addlast ("encoder", New Stringencoder ());                        Pipeline.addlast ("Handler", new Simplechannelinboundhandler<string> () {@Override                            protected void channelRead0 (Channelhandlercontext ctx, String msg) throws Exception { System.out.println (MSg);                }                    });            }            });            Channel ch = b.connect ("127.0.0.1", 7777). Sync (). Channel ();            BufferedReader in = new BufferedReader (new InputStreamReader (system.in));            String line = null;                while (true) {line = In.readline ();                if ("Close". Equals (line)} {break;            } ch.writeandflush (line + ' \ n ');        } ch.close (). sync ();        } catch (Exception e) {e.printstacktrace ();        } finally {group.shutdowngracefully (); }    }

The above code has a special place is that it only needs a thread pool, the server set Bossgroup the content of the chapter should also be easy to understand, the main thread of the server is actually blocked by SELECT, so the server Netty for the main thread is also referred to the thread pool, the client does not exist this problem.

3.Netty Core Concept

The above is a very basic demo, but the perfectly formed (perhaps not all), it gives a few important concepts in the Netty.

Bootstrap or Serverbootstrap:netty startup class, the basic parameters, the selection will be set here to complete.

Eventloopgroup or a thread pool in the Eventloop:netty package, you need to select the appropriate thread pool for the channel

Channel:netty for different IO processing is determined by the channel, there are other core concepts in the channel, not introduced here

Handler: Processing the corresponding classes for each of the IO lifecycle nodes, Handler also produces a series of concepts, which are described later.

Future or promise: This is the core of the asynchronous, it is important to get the result of asynchronous operation.

These 5 are the core content of the demo, in fact Netty is very complex, from these core will lead to other core content. This is not an introduction and the relevant chapters are explained.

4. PostScript

This section is mainly through the previous chapters, with Netty and Java examples, a primer on Netty, with the Java example of the foundation, there will be no reason why the simple configuration of Netty can ultimately achieve the desired effect is unknown. Think about it to understand how Netty's NiO is handled. The following chapters will take the Netty core concept as a theme and introduce a structure of the Netty overall.

The Netty implementation of NIO (3)

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.