Netty Introduction (a): 0 basic "HelloWorld" detailed picture and text steps

Source: Internet
Author: User
Tags set socket

Because the next project to use Netty, so to understand this program, but the online tutorials are a little bit basic, so, write an article for the Netty 0 basis, by the way also recorded.

First throw a few reference pages to learn:

Netty Official api:http://netty.io/4.1/api/index.html

Netty Chinese Guide: https://waylau.com/netty-4-user-guide/(from personal)

Knowledge on the basics of NiO: https://my.oschina.net/andylucc/blog/614295

Http://www.cnblogs.com/dolphin0520/p/3919162.html

http://blog.csdn.net/wuxianglong/article/details/6604817

What I use here:

Netty Version: Netty-5.0.0.alpha2 http://files.cnblogs.com/files/applerosa/netty-5.0.0.Alpha2.7z

Maven dependencies:

<dependency>    <groupId>io.netty</groupId>    <artifactid>netty-all</artifactid >    <version>5.0.0.Alpha2</version></dependency>

Okay, here we go.

First, you want to build a Java project, as for the general project or MAVEN project, to see their preferences, because I am just doing for learning, built a common project, and then the download of the jar package into the LIB, the introduction can be.

  

Second, we need to figure out what Netty is.

The official introduction is: Netty is a Java open source framework provided by JBoss. Netty provides asynchronous, event-driven network application frameworks and tools for rapid development of high-performance, high-reliability network servers and client programs.

And then we simply understand that this thing is a program, what? Netty is a wrapper for the Java socket NOI. A similar feature is the Apache Mina.

In contrast to Tomcat, a Web server, which is primarily about providing Web protocol-related services, Netty is a network server that is in a lower-level web framework, That means you can use Netty to mimic Tomcat to make a Web container that provides HTTP services.

  

Plainly, it is a way to handle the socket. If you want to know the details, you can visit the official introduction.

  

Third, back to the point we began to write the so-called "Hello World"

Here, is that our communication is based on a certain protocol, such as our common Web project, the front desk (browser) Send a request, the background to make corresponding return the corresponding results, this communication process is also the case.

In the official guide to Netty, it is said that the simplest protocol in the world is not ' Hello, world! ' but DISCARD (abandon service). This protocol will discard any received data without responding. Is your client sends a message, good, sent past, the server also received, but abandoned.

Plainly, you send a message to me, I received, but I directly abandoned the news, ignore you.

Second, about Netty, the first thing to figure out, this is built between the client and the server.

We first say the server, the server set up the corresponding rules, and then run, waiting for the client to access or send "message." OK, let's set up the service-side code first:

The first step: establish the appropriate rules First:

Package _01discard;import Io.netty.buffer.bytebuf;import Io.netty.channel.channelhandleradapter;import Io.netty.channel.channelhandlercontext;import Io.netty.util.charsetutil;import Io.netty.util.ReferenceCountUtil /** * Service-side processing channel. This is just a print of the requested content, not any response to the request Discardserverhandler inherit from the * Channelhandleradapter, this class implements the Channelhandler interface, Channelhandler provides a number of interface methods for event handling, and then you can override these methods. Now it is only necessary to inherit the Channelhandleradapter class instead of implementing the interface method yourself. * */public class Discardserverhandler extends Channelhandleradapter {/** * Here we cover the Chanelread () event handling method. Whenever new data is received from the client, this method is called when the message is received, * in this case, the type of message received is BYTEBUF * * @param CTX * Channel processing context information * @par        AM MSG * Received message */@Override public void Channelread (Channelhandlercontext ctx, Object msg) {            try {bytebuf in = (BYTEBUF) msg;        Print the client input, transmit the character System.out.print (In.tostring (charsetutil.utf_8)); The finally {/** * bytebuf is a reference count object that must be shown to call release ()method to release.             * Remember that the responsibility of the processor is to release all reference count objects passed to the processor.        *///Discard received Data referencecountutil.release (MSG); }}/*** * This method triggers when an exception occurs * * @param CTX * @param cause */@Override public void exception Caught (Channelhandlercontext ctx, Throwable cause) throws Exception {/** * Exceptioncaught () event handling method is when the Th The Rowable object is called when the Netty is due to an IO * error or when the processor throws an exception while handling the event. In most cases, the caught exception should be recorded and the associated channel * be closed off.         However, this approach can be handled differently when encountering different exceptions, such as a response message that you might want to send an error code before closing the connection.        *///Abnormal Turn off cause.printstacktrace ();    Ctx.close (); }}

Step two: We need to apply the appropriate rules. That is, we have established rules for receiving messages, but what is the use of light to establish rules, just a rule, we need to "apply" this rule, usually our usual "run".

Package _01discard;import Io.netty.bootstrap.serverbootstrap;import Io.netty.channel.channelfuture;import Io.netty.channel.channelinitializer;import Io.netty.channel.channeloption;import Io.netty.channel.EventLoopGroup ; Import Io.netty.channel.nio.nioeventloopgroup;import Io.netty.channel.socket.socketchannel;import io.netty.channel.socket.nio.nioserversocketchannel;/** * Discard any incoming data to start the server Discardserverhandler */public class    discardserver {private int port;        public discardserver (int port) {super ();    This.port = port; The public void run () throws Exception {/*** * Nioeventloopgroup is a multithreaded event circulator to handle I/O operations, * Netty provides Many different implementations of Eventloopgroup are used to handle different transport protocols. In this example we have implemented a service-side application, * so there will be 2 nioeventloopgroup to be used.         The first one is often called the ' boss ', which is used to receive incoming connections.         * The second is often called ' worker ' to handle the connection that has been received, and once the ' boss ' receives the connection, it registers the connection information with the ' worker '.         * How to know how many threads have been used and how to map to the channels that have been created depends on the implementation of Eventloopgroup, * and can be configured with constructors to configure their relationships. */Eventloopgroup Bossgroup = new Nioeventloopgroup ();        Eventloopgroup Workergroup = new Nioeventloopgroup ();        System.out.println ("Ready to run Port:" + port); try {/** * serverbootstrap is a secondary startup class that initiates the NIO service you can use the channel directly in this service */ServerB            Ootstrap B = new Serverbootstrap ();            /** * This step is required, if not set group will be reported Java.lang.IllegalStateException:group not * Set Exception */            b = B.group (Bossgroup, Workergroup);             /*** * Serversocketchannel is implemented on the basis of NiO selector, which is used to receive new connections * Here tells the channel how to get a new connection.            */b = B.channel (Nioserversocketchannel.class); /*** * The event handler class here is often used to handle a recent channel that has been received.             Channelinitializer is a special processing class, * His purpose is to help users configure a new channel. * Perhaps you want to implement your Web program by adding some processing classes like Nettyserverhandler to configure a new channel * or its corresponding channelpipeline.             When your program becomes complex, you may add more processing classes to pipline, and then extract these anonymous classes onto the topmost class. */b =B.childhandler (New channelinitializer<socketchannel> () {//(4) @Override public void Initchannel (Socketchannel ch) throws Exception {Ch.pipeline (). AddLast (New Discardserverhandler ());//D                    Emo1.discard//Ch.pipeline (). AddLast (New//Responseserverhandler ());//demo2.echo            Ch.pipeline (). AddLast (New//Timeserverhandler ());//demo3.time}            }); /*** * You can set the configuration parameters specified here for the channel implementation.             We are writing a TCP/IP server, * so we are allowed to set socket parameter options such as Tcpnodelay and KeepAlive.             * Please refer to the channeloption and detailed channelconfig implementation of the interface documentation so that you can have a general understanding of channeloptions.            */b = b.option (Channeloption.so_backlog, 128);             /*** * OPTION () is provided to Nioserversocketchannel to receive incoming connections.             * Childoption () is provided to the connection received by the parent pipe Serverchannel, which is also nioserversocketchannel in this example. */b = B.childoption (channeloption.so_keepalive, true);            /*** * Bind the port and start to receive incoming connections */channelfuture f = b.bind (port). sync ();        /** * This will wait until the socket is closed */F.channel (). Closefuture (). sync ();            } finally {/*** * closed */workergroup.shutdowngracefully ();        Bossgroup.shutdowngracefully ();   }    }

Run the rule public static void main (string[] args) throws Exception {int port; if (Args.length > 0) {port = Integer.parseint (Args[0]); } else {port = 8080; } new Discardserver (port). Run (); System.out.println ("Server:run ()"); }}

The third step: we now have the corresponding rules have been established, and the "Run" rule code is OK, so run the above public static void Main (string[] args) to start the server.

  

At this point the server is already running, waiting for the status of the access.

Client

Because this is a simple demo, we use Telnet to act as a client. Of course, the project must be tailored to the needs.

First open the terminal, I here is the Windows system, take this as an example, open the CMD window;

  

Type telnet 127.0.0.1 8,080 to go back to the Telnet terminal

  

Here to add that the win system by default is not to turn on the Telnet client, the need for friends to Control Panel >> program >> Open or close the Windows function inside the check box, such as

  

Well, by the step of the Telnet client, you can test the message.

Add, the default Telnet client input is not displayed, but after the input, the console has an output that means you run through the process. Such as:

You also use CTRL +] on the terminal to display, such as:

Come here, the whole process is probably what it looks like, in the heart there are numbers, and then learn the normal framework, the beginning of the road bar.

Netty Introduction (a): 0 basic "HelloWorld" detailed picture and text steps

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.