Netty Introduction Example and Analysis

Source: Internet
Author: User
Tags jboss


What is Netty? Here is a brief description of 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.

Write a simple example below:1.client Detail Analysis
ChannelFactory is the primary interface that creates a channel (and a detailed communication entity associated with it, such as a network socket). For example, Nioserversocketchannelfactory creates a channel with NIO-based service sockets as the underlying communication entity. Once a new channel is created. Then the corresponding channelpipeline will start to deal with the related channelevents.  
Nioclientsocketchannelfactory will create an NIO-based socketchannel of the client. Use a non-clogging IO model to efficiently handle these concurrent connections. There are two types of threads, boss thread and worker thread, and each nioclientsocketchannelfactory has a boss thread. It is primarily a request to be made when attempting to make a connection. Once the connection is successful, the connected channel is delivered to a worker thread. The worker thread then runs the non-clogging read-write service for one or more channels.

Clientbootstrap is simply an auxiliary function that does not allocate or manage any resources, and the management resource is completed by the ChannelFactory specified in the constructor . So it is possible to derive multiple clientbootstrap from the same ChannelFactory . This allows different settings to be applied to different channel types. the Connect () method attempts to establish a connection based on the specified socketaddress, assuming that the local address is not set, and that it is actively assigned itself, 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 number of references, Of course they are in order, and we are able to join them on our own.

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 the client, just the ChannelFactory here. Bootstrap are to satisfy the characteristics of the server.

Nioserversocketchannelfactory creates a server-side, NiO-based Serversocketchannel. is still non-clogging mode.

each bound Serversocketchannel has its own boos thread, which, for example, turns on two ports 80,443. Then there will be two boss thread, each responsible for the connection request of the port, until the port is unbound, and then the accepted connection request is given to the worker thread to handle.


This is the Clientbootstrap and serverbootstrap for connection transmission. If you want to use UDP, choose Connectionlessbootstrap.
3. The common use of channelhandler will be dealt with in detail based on the detailed event type. Involved in the reading and writing pipeline. And there's a nasty situation.


A simple Netty example: 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 ();}}



Netty Introduction Example and Analysis

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.