PackageCom.hjp.netty.netty;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 {//Configure server-side thread groups, two thread groups, one for server-side receive client connections, and another for Socketchannel network reads and writesEventloopgroup Bossgroup =NewNioeventloopgroup (); Eventloopgroup Workergroup=NewNioeventloopgroup (); Try { //Serverbootstrap is used to start the secondary startup class on the NIO server to reduce server-side development complexityServerbootstrap bootstrap =NewServerbootstrap (); Bootstrap.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Option (Channeloption.so_backlog,1024). Childhandler (NewChildchannelhandler ()); //bind port, synchronization waits for successChannelfuture future=Bootstrap.bind (port). sync (); //wait for the server to listen port shutdownFuture.channel (). Closefuture (). sync (); }finally { //graceful exit, freeing thread resourcesbossgroup.shutdowngracefully (); Workergroup.shutdowngracefully (); } } Private classChildchannelhandlerextendsChannelinitializer<socketchannel>{ protected voidInitchannel (Socketchannel Socketchannel)throwsException {socketchannel.pipeline (). AddLast (NewTimeserverhandler ()); } } Public Static voidMain (string[] args)throwsexception{intport=8080; if(args!=NULL&&args.length>0){ Try{Port=integer.valueof (args[0]); }Catch(NumberFormatException e) {}}Newtimeserver (). bind (port); }}
Timeserver
PackageCom.hjp.netty.netty;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerAdapter;ImportIo.netty.channel.ChannelHandlerContext;Importjava.util.Date; Public classTimeserverhandlerextendsChannelhandleradapter {@Override Public voidExceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {ctx.close (); } @Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {bytebuf bytebuf=(BYTEBUF) msg; byte[] request=New byte[Bytebuf.readablebytes ()]; Bytebuf.readbytes (Request); String Body=NewString (Request, "UTF-8"); System.out.println ("The time server receive order:" +body); String currenttime= "QUERY time ORDER". Equalsignorecase (body)?NewDate (). toString (): "Bad ORDER"; BYTEBUF Response=Unpooled.copiedbuffer (Currenttime.getbytes ()); Ctx.write (response); } @Override Public voidChannelreadcomplete (Channelhandlercontext ctx)throwsException {ctx.flush (); }}
Timeserverhandler
PackageCom.hjp.netty.netty;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 voidConnect (String Host,intPortthrowsException {//Configuring client NiO thread GroupsEventloopgroup Group =NewNioeventloopgroup (); Try{Bootstrap Bootstrap=NewBootstrap (); Bootstrap.group (Group). Channel (Niosocketchannel.class). Option (Channeloption.tcp_nodelay,true). Handler (NewChannelinitializer<socketchannel>() { protected voidInitchannel (Socketchannel Socketchannel)throwsException {socketchannel.pipeline (). AddLast (NewTimeclienthandler ()); } }); //initiates an asynchronous connection operation, waiting for the connection to succeed synchronouslyChannelfuture future=Bootstrap.connect (host,port). sync (); //waiting for client link to closeFuture.channel (). Close (). sync (); }finally { //Graceful exit, free NIO thread groupgroup.shutdowngracefully (); } } Public Static voidMain (string[] args)throwsexception{intport=8080; if(args!=NULL&&args.length>0){ Try{Port=integer.valueof (port); }Catch(NumberFormatException e) {}}NewTimeclient (). Connect ("127.0.0.1", Port); }}
timeclient
PackageCom.hjp.netty.netty;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerAdapter;ImportIo.netty.channel.ChannelHandlerContext;ImportJava.util.logging.Logger; Public classTimeclienthandlerextendsChannelhandleradapter {Private Static FinalLogger Logger = Logger.getlogger (Timeclienthandler.class. GetName ()); Private FinalBytebuf Firstmessage; PublicTimeclienthandler () {byte[] request = "QUERY time ORDER". GetBytes (); Firstmessage=Unpooled.buffer (request.length); Firstmessage.writebytes (Request); } @Override Public voidExceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {logger.warning ("Unexpected exception from downstream:" +cause.getmessage ()); Ctx.close (); } @Override Public voidChannelactive (Channelhandlercontext ctx)throwsException {ctx.writeandflush (firstmessage); } @Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {bytebuf bytebuf=(BYTEBUF) msg; byte[] request=New byte[Bytebuf.readablebytes ()]; Bytebuf.readbytes (Request); String Body=NewString (Request, "UTF-8"); System.out.println ("Now is" +body); }}
Timeclienthandler
Netty authoritative Guide to the Netty entry program