First Netty Program

Source: Internet
Author: User

This is I just started to learn Netty wrote the first demo, was prepared to follow the "Netty authoritative guide" of the introduction of the demo to knock aside, until I go to download the jar package to build the environment only to find that Netty No 5.x version, now the highest 4.1.9. A face Meng forced me a search just know Netty from 5.x back to 4.x, the specific reason is unclear. 4.x and 5.x, after all, a large version, the middle of a variety of similarities and differences is not my small white can now understand, or according to the official demo come. The following example is a reference to the demo in the official website guide, the approximate logic is that the client requests server time and print to the server.

Service-Side code:

1  Public classTimeserverhandlerextendschannelinboundhandleradapter{2     3     /**4 * Each incoming message is called5      * */6 @Override7      Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsexception{8Bytebuf buf =(BYTEBUF) msg;9         Try{Ten             byte[] req =New byte[Buf.readablebytes ()]; One buf.readbytes (req); AString BODY =NewString (req, "UTF-8"); -SYSTEM.OUT.PRINTLN ("The server received the request:" +body); -String time = "Query time?". Equals (body)?NewDate (). toString (): "Fail"; theBytebuf resp =Unpooled.copiedbuffer (Time.getbytes ()); - Ctx.write (resp); -}finally{ - buf.release (); +         } -     } +      A     //notifies Channelinboundhandleradapter that the last call to Channelread () is the last message in the current bulk read.  at @Override -      Public voidChannelreadcomplete (Channelhandlercontext ctx) { -         /** - * Ctx.write (RESP) is writing information to the message queue, rather than writing it every time write Socketchannel - * Ctx.flush () is the message sent in the queue to write the information in Socketchannel sent to the other side, - * Ctx.writeandflush (RESP) write directly to Socketchannel in          * */ - Ctx.flush (); to     } +      -     //exceptions that occur during processing the @Override *      Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause) { $ cause.printstacktrace ();Panax Notoginseng ctx.close (); -     } the      +}

1  Public classTimeserver {2      Public voidBindintPortthrowsexception{3         //The NIO thread group, which is designed to handle network events, is essentially a reactor thread group. 4Eventloopgroup Bosser =NewNioeventloopgroup ();//connections for server-side accept clients5Eventloopgroup worker =NewNioeventloopgroup ();//network Read and write for Socketchannel6         7         Try {8Serverbootstrap boot =NewServerbootstrap ();//Start the secondary startup class on the NIO server to reduce the complexity of the development. 9             Ten Boot.group (Bosser, worker) One. Channel (Nioserversocketchannel.class) A. option (Channeloption.so_backlog, 1024)//Configuring TCP Parameters -. Childhandler (NewChannelinitializer<socketchannel> () {//used to process network IO events (logging, encoding of messages) - @Override the                 protected voidInitchannel (Socketchannel ch)throwsException { -Ch.pipeline (). AddLast (NewTimeserverhandler ()); -                 } -             }); +              -Channelfuture CF = Boot.bind (port). sync ();//asynchronously binds the server, calling the sync () method to block the wait until the binding is complete.  +Cf.channel (). Closefuture (). sync ();//gets the channelfuture and blocks the current thread until it finishes.  A}finally{ atBosser.shutdowngracefully ();//Release All Resources - worker.shutdowngracefully (); -         } -          -     } -      in      -      Public Static voidMain (string[] args) { to         intPort = 8080; +         Try { -             Newtimeserver (). bind (port); the}Catch(Exception e) { * e.printstacktrace (); $         }Panax Notoginseng     } -}

Client code:

1  Public classTimeclienthandlerextendschannelinboundhandleradapter{2     3     //will be called after the connection to the server has been established4 @Override5      Public voidchannelactive (Channelhandlercontext ctx) {6         byte[] req = "Query time?". GetBytes ();7Bytebuf Firstmessage =Unpooled.buffer (req.length);8 firstmessage.writebytes (req);9 Ctx.writeandflush (firstmessage);Ten     } One      A     //called when a message is received from the server - @Override -      Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsexception{ theBytebuf buf =(BYTEBUF) msg; -         byte[] resp =New byte[Buf.readablebytes ()]; - buf.readbytes (resp); -String str =NewString (resp, "UTF-8"); +SYSTEM.OUT.PRINTLN ("Server time:" +str); -     } +      A @Override at      Public voidChannelreadcomplete (Channelhandlercontext ctx) { - Ctx.flush (); -     } -   -     //exceptions that occur during processing - @Override in      Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause) { - cause.printstacktrace (); to ctx.close (); +     } -        the}

 Public classtimeclient { Public voidConnect (String Host,intPortthrowsexception{Eventloopgroup Group=NewNioeventloopgroup (); Try{Bootstrap boot=NewBootstrap (); Boot.group (Group). Channel (Niosocketchannel.class). Option (Channeloption.tcp_nodelay,true). Handler (NewChannelinitializer<socketchannel>() {@Overrideprotected voidInitchannel (Socketchannel ch)throwsException {ch.pipeline (). AddLast (NewTimeclienthandler ());                        }                            }); Channelfuture CF=Boot.connect (host, port). sync ();        Cf.channel (). Closefuture (). sync (); }finally{group.shutdowngracefully (); }    }         Public Static voidMain (string[] args) {FinalString host = "127.0.0.1"; Final intPort = 8080; Try {            Newtimeclient (). Connect (host, port); } Catch(Exception e) {System.out.println ("Client" + Thread.CurrentThread (). GetId () + "Request Exception"); }                    }}

To run the code:

The starter demo is complete, and the next step is to revise it on the demo, and I'll record the following code.

First Netty Program

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.