netty4.x Chinese Course Series (ii) Hello world!

Source: Internet
Author: User

In the Chinese procedural world. We are all learning Hello world! Grow up slowly. Gradually from ignorance to familiarity with mastery.

The second chapter begins with Hello World and tells Netty's Chinese course.

Start by creating a Java project. A package that introduces a Netty framework. This step I did not repeat at the end of this series of tutorials.

Let's take a look at the project drawing for my example:

1. Download and add the Netty framework to the project

Netty package Everyone can from Netty official website: http://netty.io/downloads.html download

: Netty offers three major versions of the framework package for everyone to download.

Version 3.9 Final indicates that this version is the latest version in the 3.x version. Final means that the feature no longer continues to add updates. Provide continued updates only for bug fixes, and so on.

The 5.x version starts then. Problems such as stable operation cannot be ruled out. Plus the 5.x is slightly modified on the 4.x version. Before the 5.x stabilizes. Not recommended for everyone to learn to use.

This tutorial is based on the netty4.x version.

The author is also from the 3.6 version, after a rather painful period of time only to be considered as a real over-4.x version.

Unzip after download. You can see such a directory structure. It's very clear.

The first folder jar is the folder of the jar package. The second Javadoc is an API document. The third License folder is an open source authorization file (which can be ignored directly).

The Javadoc folder below is a jar package. can be extracted directly. The extracted folder is the API document (in the context of the page).

There are a lot of jar packages and a All-in-one folder inside the Jar folder. are part of the Netty framework. There are two files in the All-in-one. One is a jar package and the other is the corresponding source code package. The purpose of this is to give programmers the option to add their own required packages.

If the reader is a beginner. It is recommended to apply the jar package directly inside the All-in-one. If you are familiar with Netty, you can add different jar packages depending on your project needs.

2. Create the Server service side

Netty creation is all implemented from Abstractbootstrap. The client is bootstrap, and the server is Serverbootstrap.

  

2.1 Creating a HelloServer
Package Org.example.hello;import Io.netty.bootstrap.serverbootstrap;import Io.netty.channel.channelfuture;import Io.netty.channel.eventloopgroup;import Io.netty.channel.nio.nioeventloopgroup;import Io.netty.channel.socket.nio.nioserversocketchannel;public class HelloServer {/** * port address for server monitoring */privat        e static final int portnumber = 7878; public static void Main (string[] args) throws Interruptedexception {Eventloopgroup Bossgroup = new Nioeventloopgro        Up ();        Eventloopgroup Workergroup = new Nioeventloopgroup ();            try {serverbootstrap b = new Serverbootstrap ();            B.group (Bossgroup, Workergroup);            B.channel (Nioserversocketchannel.class);            B.childhandler (New Helloserverinitializer ());            The server-bound port listens channelfuture f = b.bind (portnumber). sync ();            The listener server shuts down the Listener F.channel (). Closefuture (). sync (); can be abbreviated AS/* B.bind (portnumber). sync (). Channel (). ClosefuTure (). sync ();            */} finally {bossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully (); }    }}

Eventloopgroup is a new concept presented in the 4.x release. For the management of Channel. Two service-side required. As in version 3.x, one is a boss thread and one is a worker thread.

B.childhandler (New Helloserverinitializer ()); Used to add related handler

Server-side simple code, there really is no way to streamline the feeling. is a binding port operation.

2.2 Creating and implementing Helloserverinitializer

The Helloserverinitializer in HelloServer is implemented here.

First we need to be clear about what we are going to do. Very simple. helloworld!. We want to implement a feature that sends text like a server. Service side if it is best to return the message to the client, then the client to display.

The requirements are simple. Then we are ready to begin to realize.

Delimiterbasedframedecoder Netty The example provided on the official website shows that a decoder can be easily split with messages.

Second, we found the string decoding encoder in decoder. are provided to us by the official website.

 1 package Org.example.hello; 2 3 Import Io.netty.channel.ChannelInitializer; 4 Import Io.netty.channel.ChannelPipeline; 5 Import Io.netty.channel.socket.SocketChannel; 6 Import Io.netty.handler.codec.DelimiterBasedFrameDecoder; 7 Import Io.netty.handler.codec.Delimiters; 8 Import Io.netty.handler.codec.string.StringDecoder; 9 Import io.netty.handler.codec.string.stringencoder;10 One public class Helloserverinitializer extends channelinitializer<socketchannel> {@Override14 protected void Initchannel (Socketchannel ch) throws Exc eption {Channelpipeline pipeline = Ch.pipeline (), 16 17//decoder with ("\ n") as the end segment ( "Framer", New Delimiterbasedframedecoder (8192, Delimiters.linedelimiter ())); 19 20//String decoding and encoding pipeline . AddLast ("Decoder", New Stringdecoder ()); Pipeline.addlast ("Encoder", New Stringencoder ()); 23 24//own logos Series Handler25 Pipeline.addlast ("handler", New Helloserverhandler ()); 26}27} 

The above three decoding and encoding are all systems.

Besides, what about our own handler? At the end we add one of our own handler used to write our own processing logic.

2.3 Add your own logic Helloserverhandler

Own handler We here first to inherit extends recommended simplechannelinboundhandler<c>. Here c, because we need to send a string. The c here is rewritten as a string.

  

 1 package Org.example.hello; 2 3 Import java.net.InetAddress; 4 5 Import Io.netty.channel.ChannelHandlerContext; 6 Import Io.netty.channel.SimpleChannelInboundHandler; 7 8 public class Helloserverhandler extends simplechannelinboundhandler<string> {9 @Override11 prot ected void ChannelRead0 (Channelhandlercontext ctx, String msg) throws Exception {12//Receive message Direct print output System . Out.println (Ctx.channel (). Remoteaddress () + "Say:" + msg); 14 15//Return client Message-I've received your message. CTX . Writeandflush ("Received your Message!\n"); 17}18 19/*20 * 21 * Overwrite Channelactive method when channel is enabled Trigger (at the time of establishing the connection) * * channelactive and channelinactive in the following content, here first do not do a detailed description of the * */25 @Override26 PU Blic void Channelactive (Channelhandlercontext ctx) throws Exception {System.out.println SS: "+ Ctx.channel (). Remoteaddress () +" active! "); Ctx.writeandflush ("Welcome to "+ inetaddress.getlocalhost (). GetHostName () +" service!\n "); super.channelactive (CTX); 33 }34}

The channelhandlercontent comes with a Writeandflush method. The function of the method is to write buffer and swipe in.

Note: there is a big difference here in the 3.x version. The Write () method is flush automatically in the 3.x version. The same is true in the previous versions of the 4.x version. However, after the 4.0.9 is modified to Writeandflush. The normal write method will not send a message. You need to flush () one time after write manually

Channeactive here means triggering when the connection is active (established). The remote address of the output message source. and return the welcome message.

The role of channelRead0 here is similar to the 3.x version of Messagereceived (). Can be used as a trigger for every time a message is received.

Our code here is to return the client a string "Received your message!".

  Note: the "\ n" at the very back of the string is required. Because our decoder in front of Delimiterbasedframedecoder is a string ending with "\ n". If there is no such character. There is a problem with decoding.

2.Client Client

Similar to the server-side code. We do not make a specific explanation.

Directly on the sample code:

  

 1 package Org.example.hello; 2 3 Import Io.netty.bootstrap.Bootstrap; 4 Import Io.netty.channel.Channel; 5 Import Io.netty.channel.EventLoopGroup; 6 Import Io.netty.channel.nio.NioEventLoopGroup; 7 Import Io.netty.channel.socket.nio.NioSocketChannel; 8 9 Import java.io.bufferedreader;10 import java.io.ioexception;11 import java.io.inputstreamreader;12 public class He      lloclient {public static String host = "127.0.0.1"; n-public static int port = 7878;17 18/**19 * @param ARGS20 * @throws interruptedexception * @throws ioexception */23 public static void Mai         N (string[] args) throws Interruptedexception, IOException {eventloopgroup group = new Nioeventloopgroup (); 25 try {Bootstrap b = new Bootstrap (); B.group (group). Channel (Niosocketchan Nel.class) Handler (new Helloclientinitializer ()); 30 31//Connection service end Channel ch = b.co Nnect (Host, Port). sync (). Channel (); 33 34//Console input BufferedReader in = new BufferedReader (New InputS Treamreader (system.in)); (;;)                 {PNS String line = In.readline (); + if (line = = null) {continue;40 }41/*42 * Send the text entered in the console to the server and end with "\ r \ n" 43 * The reason for using \ r \ nthe end is because I Delimiterbasedframedecoder frame decoding was added to the handler. 44 * This decoder is a decoder based on the \ n sign bit delimiter.         So the end of each message must be added \ */46 Ch.writeandflush (line + "\ r \ n") is not recognized and decoded; 47}48 } finally {//the connection is closed automatically on shutdown.50 group.shutdowngracefull Y (); 51}52}53}

The following is the Helloclientinitializer code seems to be exactly the same as the server. I didn't watch. In fact, the encoding and decoding are relative. Multi-server and client are decoded and encoded. to communicate.

  

 1 package Org.example.hello; 2 3 Import Io.netty.channel.ChannelInitializer; 4 Import Io.netty.channel.ChannelPipeline; 5 Import Io.netty.channel.socket.SocketChannel; 6 Import Io.netty.handler.codec.DelimiterBasedFrameDecoder; 7 Import Io.netty.handler.codec.Delimiters; 8 Import Io.netty.handler.codec.string.StringDecoder; 9 Import io.netty.handler.codec.string.stringencoder;10 One public class Helloclientinitializer extends channelinitializer<socketchannel> {@Override14 protected void Initchannel (Socketchannel ch) throws Exc eption {Channelpipeline pipeline = Ch.pipeline (); 16 17/*18 * This place must correspond to the service side. Otherwise the decoding and encoding 19 * 20 * decoding and encoding will not be normal. I'll give you a detailed explanation in the next one. Again for the time being not to do a detailed description of * * */23 pipeline.addlast ("Framer", New Delimiterbasedframedecoder (8192, Delimi Ters.linedelimiter ())), Pipeline.addlast ("Decoder", New Stringdecoder ()), Pipeline.addlast ("Encoder",  New Stringencoder ()); 26 27       Client Logic pipeline.addlast ("handler", New Helloclienthandler ()); 29}30} 

Hellclienthandler:

  

1 package Org.example.hello; 2  3 import io.netty.channel.ChannelHandlerContext; 4 import io.netty.channel.SimpleChannelInboundHandler; 5  6 public class Helloclienthandler extends simplechannelinboundhandler<string> {7  8     @Override 9     protected void channelRead0 (Channelhandlercontext ctx, String msg) throws Exception {ten         System.out.println ( "Server say:" + msg);     }13     @Override15 public     void channelactive (Channelhandlercontext ctx) Throws Exception {         System.out.println ("Client active");         super.channelactive (CTX);     }19 20     @Override21 public     void Channelinactive (Channelhandlercontext ctx) throws Exception {         System.out.println ("Client close");         super.channelinactive (CTX);     }25}

Here are a few results graphs:

The client in connection setup is outputting the client active information and receiving the welcome message returned by the server.

Enter Hello World! Enter to send a message. The service-side response return message has been accepted.

1. Client Console

2. Service-side Console

netty4.x Chinese Course Series (ii) Hello world!

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.