Netty Delimiter Decoder code examples and analysis

Source: Internet
Author: User
Tags throwable

[TOC]

Netty Delimiter Decoder code examples and analysis

Through the use of special decoder, can solve the problem of TCP Netty, the previous "Netty Linebasedframedecoder decoder use and analysis: Solve the problem of TCP sticky packet" through the use of line decoder to solve the problem of TCP sticky packet, This means that both the server side of the Netty and the client need to stitch the line breaks at the end of the message before each request message is sent.

In addition to using the line decoder, Netty also provides a universal delimiter decoder, the delimiter that can be customized for a message, which is the DelimiterBasedFrameDecoder delimiter decoder.

The following sample code comes from chapter 5th of the Netty Authoritative guide, which simulates the Echo service, which is similar to ping, where the client echoes a message to the server and the server responds.

It is still important to note that the code has been partially modified, and some comments and analyses have been added to the individual.

Service-Side Echoserver.java
Package Cn.xpleaf.netty;import Io.netty.bootstrap.serverbootstrap;import Io.netty.buffer.bytebuf;import Io.netty.buffer.unpooled;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;import Io.netty.handler.codec.DelimiterBasedFrameDecoder; Import Io.netty.handler.codec.string.stringdecoder;public class Echoserver {public void bind (int port) throws Exceptio        n {//Configure the NIO thread group on the server Eventloopgroup bossgroup = new Nioeventloopgroup ();        Eventloopgroup Workergroup = new Nioeventloopgroup ();            try {serverbootstrap b = new Serverbootstrap (); B.group (Bossgroup, Workergroup). Channel (nioserversocketchannel.class). Option (channeloption . So_backlog, 1024x768). ChiLdhandler (New channelinitializer<socketchannel> () {@Override protected void I                        Nitchannel (Socketchannel ch) throws Exception {//build Delimiterbasedframedecoder decoder delimiter                        Bytebuf delimiter = Unpooled.copiedbuffer ("$_". GetBytes ()); Add Delimiterbasedframedecoder decoder to pipeline//1024 indicates the maximum length of a single message, and when the length is reached, the delimiter is still not found and thrown Toolongframeex                        Ceptio exception//prevents memory overflow due to exception code stream missing delimiter, which is the reliability protection of the Netty decoder///The second parameter is the delimiter buffer object                        Ch.pipeline (). AddLast (New Delimiterbasedframedecoder (1024x768, delimiter));                        Add the Stringdecoder decoder to decode the bytebuf into a String Object Ch.pipeline (). AddLast (New Stringdecoder ());                    Add Business Processing Handler ch.pipeline (). AddLast (New Echoserverhandler ());            }                }); Bind port, synchronization waits for success Channelfuturef = b.bind (port). sync ();        Wait for the service-side listener port to close F.channel (). Closefuture (). sync ();            } finally {//gracefully exits, releasing thread pool resource bossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully ();        }} public static void Main (string[] args) throws Exception {int port = 8080;            if (args! = null && args.length > 0) {try {port = integer.valueof (port); } catch (NumberFormatException e) {//Todo:handle exception}} new Echoserver (    ). bind (port); }}
Echoserverhandler.java
Package Cn.xpleaf.netty;import Io.netty.buffer.bytebuf;import Io.netty.buffer.unpooled;import Io.netty.channel.channelhandleradapter;import Io.netty.channel.channelhandlercontext;import    Io.netty.channel.channelinboundhandleradapter;public class Echoserverhandler extends Channelinboundhandleradapter {    private int counter = 0; @Override public void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {String BODY = (Strin        g) msg; Counter's role is to mark this as the number of times the client has received the request System.out.println ("This is:" + ++counter + "The" the "the" the "" + "): [+ body +]        ");        Because the settings Delimiterbasedframedecoder filter out the delimiter,//So return to the client needs at the end of the request message stitching delimiter "$_" body + = "$_";        Bytebuf echo = Unpooled.copiedbuffer (Body.getbytes ());    Ctx.write (Echo);    } @Override public void Channelreadcomplete (Channelhandlercontext ctx) throws Exception {Ctx.flush (); } @Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause{//exception occurred, close link ctx.close (); }}
Client Echoclient.java
Package Cn.xpleaf.netty;import Io.netty.bootstrap.bootstrap;import Io.netty.buffer.bytebuf;import Io.netty.buffer.unpooled;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;import Io.netty.handler.codec.delimiterbasedframedecoder;import  Io.netty.handler.codec.string.stringdecoder;public class Echoclient {public void connect (int port, string host) throws        Exception {//Configure client NIO thread Group Eventloopgroup group = new Nioeventloopgroup ();            try {Bootstrap b = new Bootstrap (); B.group (Group). Channel (niosocketchannel.class). Option (Channeloption.tcp_nodelay, true). Han Dler (New channelinitializer<socketchannel> () {@Override protected VOID Initchannel (Socketchannel ch) throws Exception {//build Delimiterbasedframedecoder decoder delimiter                        Bytebuf delimiter = Unpooled.copiedbuffer ("$_". GetBytes ()); Add Delimiterbasedframedecoder decoder to pipeline//1024 indicates the maximum length of a single message, and when the length is reached, the delimiter is still not found and thrown Toolongframeex                        Ceptio exception//prevents memory overflow due to exception code stream missing delimiter, which is the reliability protection of the Netty decoder///The second parameter is the delimiter buffer object                        Ch.pipeline (). AddLast (New Delimiterbasedframedecoder (1024x768, delimiter));                        Add the Stringdecoder decoder to decode the bytebuf into a String Object Ch.pipeline (). AddLast (New Stringdecoder ());                    Add Business Processing Handler ch.pipeline (). AddLast (New Echoclienthandler ());            }                });            Initiates an asynchronous connection operation channelfuture F = b.connect (host, port). sync ();        Wait for the client link to close F.channel (). Closefuture (). sync (); } finally{//Graceful exit, release of NiO thread Group group.shutdowngracefully ();        }} public static void Main (string[] args) throws Exception {int port = 8080;            if (args! = null && args.length > 0) {try {port = integer.valueof (port); } catch (NumberFormatException e) {//takes the default value}} new Echoclient (). Connect (Port, "    localhost "); }}
Echoclienthandler.java
Package Cn.xpleaf.netty;import Io.netty.buffer.bytebuf;import Io.netty.buffer.unpooled;import Io.netty.channel.channelhandleradapter;import Io.netty.channel.channelhandlercontext;import    Io.netty.channel.channelinboundhandleradapter;public class Echoclienthandler extends Channelinboundhandleradapter {    private int counter; Static final String echo_req = "Hi, Xpleaf."    Welcome to Netty.$_ "; Public Echoclienthandler () {} @Override public void channelactive (Channelhandlercontext ctx) {//Build Byteb        UF object Bytebuf req = Unpooled.copiedbuffer (Echo_req.getbytes ());        Each time a call to Ctx.write () is written to the Bytebuf object, a Bytebuf object must be rebuilt//or the Ctx.write () cannot be used multiple times for a Bytebuf object, or an exception will occur/Send 10 requests to the server            for (int i = 0; i < i++) {Ctx.writeandflush (Unpooled.copiedbuffer (Echo_req.getbytes ()));        Ctx.writeandflush (req); }} @Override public void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {String body = (String) msg; The role of counter is to mark the number of times the server has received a response from the service System.out.println ("This is:" + ++counter + "When you receive servers: [+ body +"]    "); } @Override public void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {ctx.cl    OSE (); }}
Test

Service-Side output:

This is : 1 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 2 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 3 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 4 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 5 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 6 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 7 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 8 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 9 times receive client : [Hi, xpleaf. Welcome to Netty.]This is : 10 times receive client : [Hi, xpleaf. Welcome to Netty.]

Client output:

This is : 1 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 2 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 3 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 4 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 5 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 6 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 7 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 8 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 9 times receive server : [Hi, xpleaf. Welcome to Netty.]This is : 10 times receive server : [Hi, xpleaf. Welcome to Netty.]

Netty Delimiter Decoder code examples and analysis

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.