Netty Introduction Example and Analysis

Source: Internet
Author: User
Tags jboss


What is Netty? Here is an introduction to the official documentation:The Netty Project is a effort to provide anasynchronous Event-driven Network application framework and tools for rapid development of maintainable high performance and high scalability protocol servers and clients. In other words, Netty area NIO client server framework which enables quick and easy development of network Applica tions such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP/IP socket server.

A simple example is written below:1. Client-side Detail Analysis
ChannelFactory is the primary interface that creates a channel (and a specific communication entity that is associated with a network socket), such as Nioserversocketchannelfactory creates a There are NIO-based service sockets as the underlying communication entities. Once a new channel is created, the corresponding channelpipeline will begin to process the associated channelevents.  
Nioclientsocketchannelfactory Creates a client-based socketchannel of NIO and uses the non-blocking IO model to efficiently handle these concurrent connections. There are two types of threads, boss thread and worker thread, each nioclientsocketchannelfactory has a boss thread, It is primarily a request to be issued when attempting to make a connection, after the connection succeeds, the connected channel is delivered to a worker thread, then the worker thread performs a non-blocking read and write service for one or more channels.

Clientbootstrap is just an auxiliary function that does not allocate or manage any resources, and the management resource is done by the ChannelFactory specified in the constructor . So it is possible to derive multiple clientbootstrap from the same ChannelFactory , thus applying different settings for different channel. the Connect () method attempts to establish a connection based on the specified socketaddress, and if the local address is not set, it is automatically assigned, equivalent to: clientbootstrap b = ....;B.connect (remoteaddress, B.getoption ("localaddress"));

static method Channels. Pipeline (Channelhandler ... handlers) creates a new channelpipeline with the Channelhandler specified by the parameter, Of Course they are in order, and we can add them all by ourselves. Public static channelpipeline pipeline(Channelhandler ... handlers) { if (handlers = = null) { throw new nullpointerexception ( "handlers");        }
channelpipeline newpipeline = pipeline ();For ( int i = 0; i < handlers. length; i + +) {Channelhandler h = handlers[i]; If (h = = null) {Break ;            }Newpipeline.addlast (Conversionutil. toString (i), h);        } return newpipeline;    }
2. Server-side Detail Analysis
The basic process of server-side building is similar to that of clients, except that the channelfactory,bootstrap in this case is to satisfy the characteristics of server. Nioserversocketchannelfactory creates a server-side, NiO-based Serversocketchannel, which is still non-blocking mode. each bound Serversocketchannel has its own boos thread, such as open listening on two port 80,443, then there will be two boss thread, each responsible for the respective port connection request,until that port is unbound, and then the accepted connection request is given to the worker thread for processing.
This is the clientbootstrap and serverbootstrap for connection transmission, if you want to use UDP, select Connectionlessbootstrap.
3. The common use of Channelhandler will be based on specific event types to make specific processing, involving the reading and writing pipeline, and there is a nasty situation.
A simple example of Netty:Timeclientl.java
Import Java.net.inetsocketaddress;import Java.util.concurrent.executors;import Org.jboss.netty.bootstrap.clientbootstrap;import Org.jboss.netty.channel.channelfactory;import Org.jboss.netty.channel.channelpipeline;import Org.jboss.netty.channel.channelpipelinefactory;import Org.jboss.netty.channel.channels;import Org.jboss.netty.channel.socket.nio.nioclientsocketchannelfactory;public Class Timeclient {public static void main (string[] args) {String host = Args[0];int port = integer.parseint (args[1]); ChannelFactory factory = new Nioclientsocketchannelfactory (Executors.newcachedthreadpool (), Executors.newcachedthreadpool ()); Clientbootstrap bootstrap = new Clientbootstrap (factory); Bootstrap.setpipelinefactory (new Channelpipelinefactory () { @Overridepublic Channelpipeline Getpipeline () throws Exception {return channels.pipeline (new TimeClientHandler2 ());}});  Bootstrap.connect (New Inetsocketaddress (host, port)); //}}


Timeclienthandler.java
Import Java.util.date;import Org.jboss.netty.buffer.channelbuffer;import Org.jboss.netty.channel.channel;import Org.jboss.netty.channel.channelhandlercontext;import Org.jboss.netty.channel.exceptionevent;import Org.jboss.netty.channel.messageevent;import Org.jboss.netty.channel.simplechannelhandler;public Class Timeclienthandler extends simplechannelhandler{@Overridepublic void messagereceived (Channelhandlercontext ctx, Messageevent e) throws Exception {Channelbuffer buffer = (channelbuffer) e.getmessage (); Long currenttimemills = Buffer.readint () * 1000L; System.out.println (New Date (Currenttimemills)); E.getchannel (). Close (); @Overridepublic void Exceptioncaught (Channelhandlercontext ctx, exceptionevent e) throws Exception {E.getcause (). Printstacktrace (); Channel C = E.getchannel (); C.close ();}}



Timeserver.java
Import Java.net.inetsocketaddress;import Java.util.concurrent.executors;import Org.jboss.netty.bootstrap.serverbootstrap;import Org.jboss.netty.channel.channel;import Org.jboss.netty.channel.channelfactory;import Org.jboss.netty.channel.channelpipeline;import Org.jboss.netty.channel.channelpipelinefactory;import Org.jboss.netty.channel.channels;import Org.jboss.netty.channel.group.channelgroup;import Org.jboss.netty.channel.group.channelgroupfuture;import Org.jboss.netty.channel.group.defaultchannelgroup;import Org.jboss.netty.channel.socket.nio.nioserversocketchannelfactory;public class Timeserver {public static Channelgroup allchannels = new Defaultchannelgroup ("Time-server");p ublic static void Main (string[] args) { ChannelFactory factory = new Nioserversocketchannelfactory (Executors.newcachedthreadpool (), Executors.newcachedthreadpool ()); Serverbootstrap bootstrap = new Serverbootstrap (factory); Bootstrap.setpipelinefactory (new Channelpipelinefactory () { @Overridepublic Channelpipeline GEtpipeline () throws Exception {return channels.pipeline (new TimeServerHandler2 (), New Timeencoder ());}); Bootstrap.setoption ("Reuseaddr", true); Bootstrap.setoption ("Child.tcpnodelay", true); Bootstrap.setoption (" Child.keepalive ", true);  Channel channel = Bootstrap.bind (new inetsocketaddress (8080)); Allchannels.add (channel);//waitforshutdowncommand (); This is a imaginary logic:for instance//when There are accepted connection we close this server; if (allchannels.size) ; =2) {channelgroupfuture f = allchannels.close (); f.awaituninterruptibly (); Factory.releaseexternalresources ();}}}



Timeserverhandler.java
Import Org.jboss.netty.buffer.channelbuffer;import Org.jboss.netty.buffer.channelbuffers;import Org.jboss.netty.channel.channel;import Org.jboss.netty.channel.channelfuture;import Org.jboss.netty.channel.channelfuturelistener;import Org.jboss.netty.channel.channelhandlercontext;import Org.jboss.netty.channel.channelstateevent;import Org.jboss.netty.channel.exceptionevent;import Org.jboss.netty.channel.simplechannelhandler;public class Timeserverhandler extends simplechannelhandler{@ overridepublic void channelconnected (Channelhandlercontext ctx, channelstateevent e) throws Exception {Channel ch = E.getchannel (); Channelbuffer time = Channelbuffers.buffer (4); sizeof Inttime.writeint ((int) (System.currenttimemillis ()/1000l + 2208988800L)); Channelfuture CF = Ch.write (time), Cf.addlistener (new Channelfuturelistener () {@Overridepublic void Operationcomplete ( Channelfuture future) throws Exception {Channel ch = future.getchannel (); Ch.close ();});} @Overridepublic void Exceptioncaught (ChannelhandlErcontext CTX, Exceptionevent e) throws Exception {E.getcause (). Printstacktrace (); Channel C = E.getchannel (); C.close ();}}



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.