Netty5 Getting Started learning Note 001

Source: Internet
Author: User
Tags getmessage

Netty Official website: http://netty.io/

This routine is written using the latest netty5.x version

Server-side:

The Timeserver time Server service side receives the client's connection request and queries the current time of the instruction, judging the correct command after the response returns the calibration time of the current server.

package c1;import io.netty.bootstrap.serverbootstrap;import io.netty.channel.channelfuture; import io.netty.channel.channelinitializer;import io.netty.channel.channeloption;import  io.netty.channel.eventloopgroup;import io.netty.channel.nio.nioeventloopgroup;import  io.netty.channel.socket.socketchannel;import io.netty.channel.socket.nio.nioserversocketchannel;/**  * server  problem with sticky bag  *  @author  xwalker */public class timeserver { Public void bind (int port)  throws Exception {//  server thread group   processing for network events   One connection for the server receiving client//  another thread group to handle Socketchannel network read and write eventloopgroup bossgroup = new  Nioeventloopgroup (); Eventloopgroup workergroup = new nioeventloopgroup (); Try {// nio server-side boot class   Reduce server Development difficulty serverbootstrap serverbootstrap = new serverbootstrap (); Serverbootstrap.group ( bossgroup, workergroup). ChaNnel (Nioserversocketchannel.class)//  similar to NiO in Serversocketchannel.option (channeloption.so_backlog, 1024 )//  Configure the TCP parameter. Childhandler (New childchannelhandler ());//  the processing class of the last bound I/O event//  handling network IO Events//  After the server starts   binds the listening port   synchronization waits successfully   notification callbacks primarily for asynchronous operations   callback handling childchannelhandlerchannelfuture f =  serverbootstrap.bind (port). sync (); System.out.println ("Timeserver-boot");//  waits for the server-side listener port to close F.channel (). Closefuture (). sync ();  finally {//  Graceful exit   release thread pool resource bossgroup.shutdowngracefully (); workergroup.shutdowngracefully (); SYSTEM.OUT.PRINTLN ("Server gracefully frees up thread resources ...");}} /** *  Network Event Processor  */private class ChildChannelHandler extends  channelinitializer<socketchannel> {@Overrideprotected  void initchannel (socketchannel &NBSP;CH)  throws exception {ch.pipeline (). AddLast (New timeserverhandler ());}} Public static void main (String[] args)  throws exception {int poRt = 8000;new timeserver (). bind (port);}} 

Timerserver receives the client's connection and read and write requests to the processor handler for event response processing, the server defines two sets of thread groups, one for handling client connections, and a set of responses to handle network IO events (socketchannel). Nioeventloopgroup is the NIO thread group provided by Netty, which is actually the reactor thread group in Java NIO.

Serverbootstrap is the Netty provided by the NIO service-side helper startup class, which reduces the development complexity of the NIO server.

Serverbootstrap needs to bind the processing class Childchannelhandler of the server network IO event to actually handle the specific IO events, such as logging, decoding the message, and so on.

Timeserverhandler needs to inherit the Netty provided by the adapter Channelhandleradapter rewrite Channelread and other methods to complete the read and write messages.

package c1;import io.netty.buffer.bytebuf;import io.netty.buffer.unpooled;import  io.netty.channel.channelhandleradapter;import io.netty.channel.channelhandlercontext;import  Java.util.date;/** * server-side Network IO event processing  *  @author  xwalker * */public  class timeserverhandler extends channelhandleradapter {@Overridepublic  void  Channelread (channelhandlercontext ctx, object msg) throws exception { SYSTEM.OUT.PRINTLN ("Server read to client request ..."); bytebuf buf= (BYTEBUF)  msg;byte[] req=new byte[buf.readablebytes ()];buf.readBytes (req); String body=new string (req, "UTF-8"); System.out.println ("The time server receive order:" +body); String curenttime= "Query time order". Equalsignorecase (Body)? New date ( System.currenttimemillis ()). ToString (): "Bad order"; Bytebuf resp=unpooled.copiedbuffer (Curenttime.getbytes ()); Ctx.write (RESP); SYSTEM.OUT.PRINTLN ("server responded");} @Overridepublic  void channelreadcomplete (CHANNELHANDLERCONTEXT&NBSP;CTX)  throws exception  {ctx.flush (); SYSTEM.OUT.PRINTLN ("Server readcomplete  response completed");} @Overridepublic  void exceptioncaught (Channelhandlercontext ctx, throwable cause) Throws exception {ctx.close (); SYSTEM.OUT.PRINTLN ("Server Exception Exits" +cause.getmessage ());}}

The server receives and processes the message request through the handler, the MSG in the Channelread is the message that the client requests, after obtains the concrete information through the decoding, completes the subsequent response according to the message format and the definition.

Bytebuf is the Bytebuffer class in Netty encapsulated and extended Java NIO, and is more sophisticated. The BYTEBUF receives and decodes the MSG into a string type and then determines that the command is accurate and responds according to the result.

Client:

Client processing is relatively simple, start the client, the link server succeeds after sending the time query instruction, waits for the server to respond.

Package c1;import io.netty.bootstrap.bootstrap;import io.netty.channel.channelfuture;import  io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import  io.netty.channel.eventloopgroup;import io.netty.channel.nio.nioeventloopgroup;import  io.netty.channel.socket.socketchannel;import io.netty.channel.socket.nio.niosocketchannel;/** *  client  There is a problem with the TCP sticky packet  *  @author  xwlaker * */public class timeclient  {/** *  Connect servers  *  @param  port *  @param  host *  @throws  exception */public void connect (int port, string host)  throws  exception {//Configuring client NiO Thread Group Eventloopgroup group = new nioeventloopgroup (); try {// Client-side Boot class   Configure Bootstrap b = new bootstrap (); B.group (group) for the client. Channel ( niosocketchannel.class). Option (channeloption.tcp_nodelay, true). HandlER (new channelinitializer<socketchannel> ()  {@Overrideprotected  void initchannel ( SOCKETCHANNEL&NBSP;CH) Throws exception {ch.pipeline (). AddLast (New timeclienthandler ());}); /Asynchronous Link server   Sync wait link succeeded Channelfuture f = b.connect (host, port). sync ();//wait for the link to close F.channel (). Closefuture (). sync ();}  finally {group.shutdowngracefully (); SYSTEM.OUT.PRINTLN ("The client gracefully frees up thread resources ...");}} Public static void main (String[] args)  throws Exception {new  Timeclient (). Connect (8000,  "127.0.0.1");}}

The client defines a set of thread groups that are used to handle network IO events with the server. The handler of thread groups, TCP parameters, and IO event handling are configured through the client-side startup class Bootstrap.

package c1;import io.netty.buffer.bytebuf;import io.netty.buffer.unpooled;import  io.netty.channel.channelhandleradapter;import io.netty.channel.channelhandlercontext;import  java.util.logging.logger;/** * client  Network IO Event processing  *  @author  xwalker * */ Public class timeclienthandler extends channelhandleradapter {private static  final logger logger=logger.getlogger (TimeClientHandler.class.getName ());p rivate   Bytebuf firstmessage;public timeclienthandler () {byte[] req = "QUERY TIME ORDER". GetBytes (); Firstmessage=unpooled.buffer (req.length); Firstmessage.writebytes (req);} @Overridepublic  void channelactive (CHANNELHANDLERCONTEXT&NBSP;CTX)  throws exception { Ctx.writeandflush (Firstmessage); SYSTEM.OUT.PRINTLN ("Client Active");} @Overridepublic  void channelread (channelhandlercontext ctx, object msg) Throws EXCEPTION&NBSP;{SYSTEM.OUT.PRINTLN ("Client Receives server response data"); bytebuf buf= (BYTEBUF)  msg;byte[] req=new byte[buf.readablebytes ()];buf.readBytes (req); String body=new string (req, "UTF-8"); System.out.println ("Now is:" +body);} @Overridepublic  void channelreadcomplete (CHANNELHANDLERCONTEXT&NBSP;CTX)  throws exception  {ctx.flush (); SYSTEM.OUT.PRINTLN ("Client Receives server Response data processing complete");} @Overridepublic  void exceptioncaught (Channelhandlercontext ctx, throwable cause) Throws exception {logger.warning ("Unexpected exception from downstream:" + Cause.getmessage ()); Ctx.close (); SYSTEM.OUT.PRINTLN ("Client exception Exit");}}

Timeclienthandler inherits the Netty provided by the handler adapter, overriding the Channelactive and Channelread methods to send a query instruction when the former channel opens the active state, which receives the server response message and decodes the output.

Operation Result:

After the client starts, the processor channelactive is called to send the query instruction, the server side receives the query instruction, returns the current time, the client receives the server response and decodes the output current time.


Netty5 Getting Started learning Note 001

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.