Netty Implementation Time Service example

Source: Internet
Author: User
Tags getmessage jboss


relevant knowledge points:[1] channelgroup is a thread-safe collection that accommodates open channel instances, allowing us to uniformly apply operations. So in the process of using, some related channel can be classified as a meaningful set, the closed channel is automatically removed from the collection, and a channel can belong to more than one channelgroup. A common scenario is to channel a set of channelsto simplify the process of closing a set of channels.
[2] because the channel in circulation is channelbuffer (can contact NiO Bytebuffer to understand), and in the internal pipeline processing may be a single object, so when received or to be sent to the end of the time need a decoding, The process of encoding: converting between objects that are actually meaningful and byte arrays.
[3] in the client and server-side pipeline handler execution sequence is different, the execution order in the client and channelpipeline the order of increase is consistent, and the server side is exactly the opposite, it is important to note, so see the codec class location is like that.
Specific code:Timeclient.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.channelfuture;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 = "localhost"; int port = 8080;if (Args.length = = 2) {host = Args[0];p ort = 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 TimeDecoder2 (), New TimeClientHandler4 ());}); Channelfuture FutuRe = Bootstrap.connect (new inetsocketaddress (host, port)); Future.awaituninterruptibly (), if (!future.issuccess ()) {Future.getcause (). Printstacktrace (); Future.getchannel (). Getclosefuture (). awaituninterruptibly (); Factory.releaseexternalresources ();}}

Timedecoder2.java
Import Org.jboss.netty.buffer.channelbuffer;import Org.jboss.netty.channel.channel;import Org.jboss.netty.channel.channelhandlercontext;import Org.jboss.netty.handler.codec.frame.framedecoder;public Class TimeDecoder2 extends framedecoder{@Overrideprotected Object decode (Channelhandlercontext CTX, channel channel, Channelbuffer buffer) throws Exception {if (Buffer.readablebytes () < 4) return Null;return new Unixtime (buffer.readint ());} }

Timeclienthandler4.java
Import Org.jboss.netty.buffer.channelbuffer;import Org.jboss.netty.buffer.channelbuffers;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 TimeClientHandler4 extends simplechannelhandler{@ overridepublic void messagereceived (Channelhandlercontext ctx, messageevent e) throws Exception {//the decoder put Unixtime Obj,so Get just what we needunixtime cur = (unixtime) e.getmessage (); SYSTEM.OUT.PRINTLN (cur); 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 {//[1]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 ();}}}

Timeserverhandler2.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 TimeServerHandler2 extends simplechannelhandler{@ overridepublic void Channelopen (Channelhandlercontext ctx, channelstateevent e) throws Exception { TimeServer.allChannels.add (E.getchannel ());} @Overridepublic void channelconnected (Channelhandlercontext ctx, channelstateevent e) throws Exception {unixtime time = New Unixtime ((int) (System.currenttimemillis ()/1000)); Channelfuture f = e.getchannel (). write (time); F.addlistener (channelfuturelistener.close);} @Overridepublic void Exceptioncaught (Channelhandlercontext ctx, exceptionevent e) throws Exception {E.getcauSe (). Printstacktrace (); Channel C = E.getchannel (); C.close ();}}

Timeencoder.java
Import Org.jboss.netty.buffer.channelbuffer;import Org.jboss.netty.buffer.channelbuffers;import Org.jboss.netty.channel.channelhandlercontext;import Org.jboss.netty.channel.channels;import Org.jboss.netty.channel.messageevent;import Org.jboss.netty.channel.simplechannelhandler;public class TimeEncoder Extends simplechannelhandler{@Overridepublic void writerequested (Channelhandlercontext ctx, messageevent e) throws Exception {unixtime time = (unixtime) e.getmessage (); Channelbuffer buf = Channelbuffers.buffer (4); Buf.writeint (Time.getvalue ()); Channels.write (CTX, E.getfuture (), buf);}}

Unixtime.java
Import Java.util.date;public class Unixtime {private int value;public unixtime (int value) {this.value = value;} public int GetValue () {return this.value;} public void SetValue (int value) {this.value = value;} @Overridepublic String toString () {//allocates A Date object and initializes it to represent the specified number//of mill Iseconds since the standard base time known as "The Epoch",//namely January 1, 1970, 00:00:00 Gmtreturn new Date (value * 1000L). toString ();}}






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.