Netty Getting Started instance

Source: Internet
Author: User

Timeserver.java

 PackageNetty.timeserver.server;ImportIo.netty.bootstrap.ServerBootstrap;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelInitializer;Importio.netty.channel.ChannelOption;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.channel.socket.nio.NioServerSocketChannel; Public classTimeserver { Public voidBindintPortthrowsException {eventloopgroup bossgroup=NewNioeventloopgroup (); Eventloopgroup Workergroup=NewNioeventloopgroup (); Try {            //Configure the server's NIO thread rentalServerbootstrap B =NewServerbootstrap (); B.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Option (Channeloption.so_backlog,1024). Childhandler (NewChildchannelhandler ()); //bind port, synchronization waits for successChannelfuture f =B.bind (port). sync (); //wait for the server to listen port shutdownF.channel (). Closefuture (). sync (); } finally {            //graceful exit, releasing thread pool resourcesbossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully (); }    }    Private classChildchannelhandlerextendsChannelinitializer<socketchannel>{@Overrideprotected voidInitchannel (Socketchannel arg0)throwsException {System.out.println ("Server Initchannel.."); Arg0.pipeline (). AddLast (NewTimeserverhandler ()); }    }     Public Static voidMain (string[] args)throwsException {intPort = 9000; if(Args! =NULL&& args.length > 0) {            Try{Port= Integer.valueof (args[0]); } Catch(NumberFormatException e) {}}Newtimeserver (). bind (port); }}

Timeserverhandler.java

 PackageNetty.timeserver.server;Importjava.util.Date;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelInboundHandlerAdapter; Public classTimeserverhandlerextendsChannelinboundhandleradapter {@Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {System.out.println ("Server Channelread.."); Bytebuf buf=(BYTEBUF) msg; byte[] req =New byte[Buf.readablebytes ()];        Buf.readbytes (req); String Body=NewString (req, "UTF-8"); System.out.println ("The time server receive order:" +body); String currenttime= "QUERY time ORDER". Equalsignorecase (body)?NewDate (System.currenttimemillis ()). ToString ():"Bad ORDER"; Bytebuf resp=Unpooled.copiedbuffer (Currenttime.getbytes ());    Ctx.write (RESP); } @Override Public voidChannelreadcomplete (Channelhandlercontext ctx)throwsException {System.out.println ("Server Channelreadcomplete.."); Ctx.flush ();//data is sent to Socketchannel after refresh} @Override Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {System.out.println ("Server Exceptioncaught..");    Ctx.close (); }}

Timeclient.java

 Packagenetty.timeserver.client;ImportIo.netty.bootstrap.Bootstrap;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelInitializer;Importio.netty.channel.ChannelOption;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.channel.socket.nio.NioSocketChannel; Public classtimeclient { Public voidConnectintPort, String host)throwsException {//Configuring client NiO thread GroupsEventloopgroup Group =NewNioeventloopgroup (); Try{Bootstrap b=NewBootstrap (); B.group (Group). Channel (Niosocketchannel.class). Option (Channeloption.tcp_nodelay,true). Handler (NewChannelinitializer<socketchannel>() {@Overrideprotected voidInitchannel (Socketchannel arg0)throwsException {System.out.println ("Client Initchannel."); Arg0.pipeline (). AddLast (NewTimeclienthandler ());            }                    }); //initiating an asynchronous join operationChannelfuture f =B.connect (host, port). sync (); //waiting for client link to closeF.channel (). Closefuture (). sync (); } finally {            //Graceful exit, free NIO thread groupgroup.shutdowngracefully (); }    }     Public Static voidMain (string[] args)throwsException {intPort = 9000; if(Args! =NULL&& args.length > 0) {            Try{Port= Integer.parseint (args[0]); } Catch(Exception e) {}}NewTimeclient (). Connect (port, "127.0.0.1"); }}

Timeclienthandler.java

 Packagenetty.timeserver.client;ImportJava.util.logging.Logger;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelInboundHandlerAdapter; Public classTimeclienthandlerextendsChannelinboundhandleradapter {Private Static FinalLogger Logger =Logger. GetLogger (Timeclienthandler.class. GetName ()); Private FinalBytebuf Firstmessage;  PublicTimeclienthandler () {byte[] req = "QUERY time ORDER". GetBytes (); Firstmessage=Unpooled.buffer (req.length);    Firstmessage.writebytes (req); } @Override Public voidChannelactive (Channelhandlercontext ctx)throwsException {//after establishing a connection with the serverSYSTEM.OUT.PRINTLN ("Client channelactive ...");    Ctx.writeandflush (Firstmessage); } @Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {System.out.println ("Client Channelread."); //after the server returns the messageBytebuf buf =(BYTEBUF) msg; byte[] req =New byte[Buf.readablebytes ()];        Buf.readbytes (req); String Body=NewString (req, "UTF-8"); System.out.println ("Now is:" +body); } @Override Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {System.out.println ("Client exceptioncaught."); //Freeing ResourcesLogger.warning ("Unexpected exception from downstream:" +cause.getmessage ());    Ctx.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.