Netty Basic Usage

Source: Internet
Author: User

1. Client

①helloclient.java

public class Helloclient {public static String host = "127.0.0.1";      public static int port = 7878; /** * @param args * @throws interruptedexception * @throws IOException */public static void Mai         N (string[] args) throws Interruptedexception, IOException {eventloopgroup workGroup = new Nioeventloopgroup ();             try {Bootstrap b = new Bootstrap ();              B.group (WorkGroup). Channel (Niosocketchannel.class). Handler (new Helloclientinitializer ());                          Connection server Channelfuture future = B.connect (host, port). sync ();             Console input BufferedReader in = new BufferedReader (new InputStreamReader (system.in)); for (;;)                 {String line = In.readline ();                 if (line = = null) {continue; }/* * Send the text entered on the console to the server and end with "\ r \ n" * It ends with \ r \ n Because we're in handle.Delimiterbasedframedecoder frame decoding was added in R. * This decoder is a decoder based on the \ n sign bit delimiter.             So the end of each message must be added \ n otherwise unrecognized and decoded * */Future.channel (). Writeandflush (line + "\ r \ n");         }} finally {//the connection is closed automatically on shutdown.         Workgroup.shutdowngracefully (); }     }}

②helloclientinitializer.java

The main function is to complete the client's codec work

public class Helloclientinitializer extends channelinitializer<socketchannel> {     protected void Initchannel ( Socketchannel ch) throws Exception {         Channelpipeline pipeline = Ch.pipeline ();          /* * This place must correspond to the service side. Otherwise, decoding and encoding will not be decoded and encoded           . * Decoding and encoding I'll explain it in detail in the next one. Again for the time being not to do a detailed description * * *         /pipeline.addlast ("Framer", New Delimiterbasedframedecoder (8192, Delimiters.linedelimiter ()));         Pipeline.addlast ("Decoder", New Stringdecoder ());         Pipeline.addlast ("encoder", New Stringencoder ());                  The logical pipeline.addlast of the client         ("handler", New Helloclienthandler ());}    }

③helloclienthandler.java

Business Processing class, there are three main methods

Called when the client establishes a connection: Channelactive method

Called when the client receives a service-side message: ChannelRead0 method

Called when the connection is broken: Channelinactive method

public class Helloclienthandler extends simplechannelinboundhandler<string> {     @Override     protected void ChannelRead0 (Channelhandlercontext ctx, String msg) throws Exception {                  System.out.println ("Server say:" + msg); 
   
    }          @Override public     void Channelactive (Channelhandlercontext ctx) throws Exception {         System.out.println ( "Client active");         Super.channelactive (CTX);     }      @Override public     void Channelinactive (Channelhandlercontext ctx) throws Exception {         System.out.println (" Client close ");         Super.channelinactive (CTX);     }}
   

2. Service-side

①helloserver.java

public class HelloServer {/** * server-side Listening port address */private static final int portnumber = 7878; public static void Main (string[] args) throws Interruptedexception {//First thread group to receive client connections Eventloopgroup Bossgro        up = new Nioeventloopgroup ();        The second thread group is used for specific business processing eventloopgroup workergroup = new Nioeventloopgroup ();            try {//Create an auxiliary class Boosatrap for a series of configuration of the server Serverbootstrap B = new Serverbootstrap ();            Join two thread groups in B.group (Bossgroup, Workergroup);            Specifies a channel B.channel (nioserversocketchannel.class) using this type of nioserversocketchannel;                        Be sure to use Childhandler to bind the specific event handler B.childhandler (New Helloserverinitializer ());                        Socketchannel configuration entry for the channel (keep connected) b.option (channeloption.so_keepalive, true);            The server-bound port listens channelfuture f = b.bind (portnumber). sync ();            The listener server shuts down the Listener F.channel (). Closefuture (). sync ();can be shortened to/* B.bind (portnumber). sync (). Channel (). Closefuture (). sync ();            */} finally {bossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully (); }    }}

②helloserverinitializer.java

The main function is to complete the service end of the codec work

public class Helloserverinitializer extends channelinitializer<socketchannel> {     @Override     protected void Initchannel (Socketchannel ch) throws Exception {         Channelpipeline pipeline = Ch.pipeline ();          Decoder pipeline.addlast ("\ n") at the end of the split ("         framer", New Delimiterbasedframedecoder (8192, Delimiters.linedelimiter () ));          String decoding and encoding         pipeline.addlast ("Decoder", New Stringdecoder ());         Pipeline.addlast ("encoder", New Stringencoder ());          Own logic handler         Pipeline.addlast ("handler", New Helloserverhandler ());}     }

③helloserverhandler.java

Service-side business processing class, mainly including channelRead0 (), Channelactive () method

Channelactive () Triggers when connection is established

CHANNELREAD0 () receiving client messages

public class Helloserverhandler extends simplechannelinboundhandler<string> {     @Override     protected void ChannelRead0 (Channelhandlercontext ctx, String msg) throws Exception {         //Receive message Direct print output         System.out.println ( Ctx.channel (). Remoteaddress () + "Say:" + msg);                  Return client Message-I have received your message         Ctx.writeandflush ("Received your Message!\n");     }          /* *       Overwrite the Channelactive method when the channel is enabled (when the connection is established)      *       * channelactive and channelinactive are described in the following sections, Here is not a detailed description      * *     /@Override public     void Channelactive (Channelhandlercontext ctx) throws Exception {                  System.out.println ("ramoteaddress:" + Ctx.channel (). Remoteaddress () + "active!");                  Ctx.writeandflush ("Welcome to" + inetaddress.getlocalhost (). GetHostName () + "service!\n");                  Super.channelactive (CTX);     }}

Netty Basic Usage

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.