Netty Introduction (i)

Source: Internet
Author: User

First, Introduction

Netty is a Web application framework based on the Java NIO Client-server, which enables rapid development of network applications such as server and client protocols using Netty. Netty provides a new way to develop Web applications, a new way to make it easy to use and highly scalable. The internal implementation of Netty is complex, but Netty provides an easy-to-use API to decouple business logic from network processing code. Netty is entirely based on NIO, so the entire netty is asynchronous.

Network applications often require a high degree of scalability, whether Netty or other Java NIO-based frameworks, providing a scalable solution. A key component of Netty is its asynchronous nature, and this article discusses synchronous (blocking) and asynchronous (non-blocking) Io to illustrate why asynchronous code is used to solve extensibility problems and how to use Asynchrony.

Second, the entry procedure

2.1 Creating a service-side

2.1.1 Creating HelloServer

 Packagecom.zy.netty.example;ImportIo.netty.bootstrap.ServerBootstrap;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.nio.NioServerSocketChannel; Public classHelloServer {/*** Port address for server monitoring*/    Private Static Final intPortNumber = 7878;  Public Static voidMain (string[] args)throwsinterruptedexception {eventloopgroup bossgroup=NewNioeventloopgroup (); Eventloopgroup Workergroup=NewNioeventloopgroup (); Try{Serverbootstrap b=NewServerbootstrap ();            B.group (Bossgroup, Workergroup); B.channel (Nioserversocketchannel.class); B.childhandler (NewHelloserverinitializer ()); //server-bound port monitoringChannelfuture f =B.bind (portnumber). sync (); //Monitoring Server shutdown monitoringF.channel (). Closefuture (). sync (); //can be shortened to            /*B.bind (portnumber). sync (). Channel (). Closefuture (). sync ();*/        } finally{bossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully (); }    }}

2.1.2 Creating and Implementing Helloserverinitializer

 Packagecom.zy.netty.example;ImportIo.netty.channel.ChannelInitializer;ImportIo.netty.channel.ChannelPipeline;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.handler.codec.DelimiterBasedFrameDecoder;Importio.netty.handler.codec.Delimiters;ImportIo.netty.handler.codec.string.StringDecoder;ImportIo.netty.handler.codec.string.StringEncoder; Public classHelloserverinitializerextendsChannelinitializer<socketchannel>{@Overrideprotected voidInitchannel (Socketchannel ch)throwsException {Channelpipeline pipeline=Ch.pipeline (); //decoder with the end of ("\ n")Pipeline.addlast ("Framer",NewDelimiterbasedframedecoder (8192, Delimiters.linedelimiter ())); //string decoding and encodingPipeline.addlast ("Decoder",NewStringdecoder ()); Pipeline.addlast ("Encoder",NewStringencoder ()); //own Logic HandlerPipeline.addlast ("Handler",NewHelloserverhandler ()); }}

2.1.3 Creating Serverhandler

 Packagecom.zy.netty.example;Importjava.net.InetAddress;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.SimpleChannelInboundHandler; Public classHelloserverhandlerextendsSimplechannelinboundhandler<string> {/*@Override protected void Channelread (Channelhandlercontext ctx, String msg) throws Exception {//Receive message directly        Print output System.out.println (Ctx.channel (). Remoteaddress () + "Say:" + msg);    Return client Message-I have received your message Ctx.writeandflush ("Received your Message!\n"); }*/    /** * Overwrite channelactive method triggers when channel is enabled (when connection is established) * * Channelactive and channelinactive are described in the following sections, which Don't make a detailed description of it first .*/@Override Public voidChannelactive (Channelhandlercontext ctx)throwsException {System.out.println ("Ramoteaddress:" + Ctx.channel (). Remoteaddress () + "Active!"); Ctx.writeandflush ("Welcome to" + inetaddress.getlocalhost (). GetHostName () + "service!\n"); Super. channelactive (CTX); } @Overrideprotected voidMessagereceived (Channelhandlercontext ctx, String msg)throwsException {System.out.println (Ctx.channel (). remoteaddress ()+ "Say:" +msg); //return Client Message-I have received your messageCtx.writeandflush ("Received Your message!\n"); }}

2.2Client Client

2.2.1 Creating helloclient

 Packagecom.zy.netty.example;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportIo.netty.bootstrap.Bootstrap;ImportIo.netty.channel.Channel;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.nio.NioSocketChannel; Public classhelloclient { Public StaticString host = "127.0.0.1";  Public Static intPort = 7878; /**     * @paramargs *@throwsinterruptedexception *@throwsIOException*/     Public Static voidMain (string[] args)throwsinterruptedexception, IOException {eventloopgroup Group=NewNioeventloopgroup (); Try{Bootstrap b=NewBootstrap (); B.group (Group). Channel (Niosocketchannel.class). Handler (NewHelloclientinitializer ()); //connecting to the service sideChannel ch =B.connect (host, port). Sync (). Channel (); //Console InputBufferedReader in =NewBufferedReader (NewInputStreamReader (system.in));  for (;;) {String Line=In.readline (); if(line = =NULL) {                    Continue; }                /** Send the text input on the console to the server and use the "\ r \ n" end to end with \ r \ n Because we have added * Delimiterbasedframedecode in handler                 R frame decoding. * This decoder is a decoder based on the \ n sign bit delimiter. So the end of each message must be added \ n Otherwise unrecognized and decoded*/Ch.writeandflush ( line+ "\ r \ n"); }        } finally {            //The connection is closed automatically on shutdown.group.shutdowngracefully (); }    }}

2.2.2 Creating and implementing Helloclientinitalizer

 Packagecom.zy.netty.example;ImportIo.netty.channel.ChannelInitializer;ImportIo.netty.channel.ChannelPipeline;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.handler.codec.DelimiterBasedFrameDecoder;Importio.netty.handler.codec.Delimiters;ImportIo.netty.handler.codec.string.StringDecoder;ImportIo.netty.handler.codec.string.StringEncoder; Public classHelloclientinitializerextendsChannelinitializer<socketchannel>{@Overrideprotected voidInitchannel (Socketchannel ch)throwsException {Channelpipeline pipeline=Ch.pipeline (); /** This place must correspond with the service side. Otherwise, decoding and encoding will not be decoded and encoded. * Decoding and encoding I'll explain it in detail in the next one. Don't do a detailed description again * **/Pipeline.addlast ("Framer",NewDelimiterbasedframedecoder (8192, Delimiters.linedelimiter ())); Pipeline.addlast ("Decoder",NewStringdecoder ()); Pipeline.addlast ("Encoder",NewStringencoder ()); //the logic of the clientPipeline.addlast ("Handler",NewHelloclienthandler ()); }}

2.2.3 Creating ClientHandler

 Packagecom.zy.netty.example;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.SimpleChannelInboundHandler; Public classHelloclienthandlerextendsSimplechannelinboundhandler<string> {    /** @Override protected void channelRead0 (Channelhandlercontext ctx, String * msg) throws Exception {* * SYSTEM.OUT.PRINTLN ("Server say:" + msg);*/@Override Public voidChannelactive (Channelhandlercontext ctx)throwsException {System.out.println ("Client Active"); Super. channelactive (CTX); } @Override Public voidChannelinactive (Channelhandlercontext ctx)throwsException {System.out.println ("Client Close"); Super. channelinactive (CTX); } @Overrideprotected voidMessagereceived (Channelhandlercontext ctx, String msg)throwsException {System.out.println ("Server say:" +msg); }}

The above example is a simplest model of server and client communication, the main principle is that the server and the client listen to the same IP port, monitor the information to respond accordingly

Netty Introduction (i)

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.