Learn Netty (vi) The TCP Sticky pack unpacking scenario

Source: Internet
Author: User
Tags throwable

TCP programming at the bottom have a sticky packet and unpacking mechanism, because we in the C/s transmission model, with the TCP protocol transmission, in the network of byte is actually like a river, TCP is like a porter, the flow from one end to the other, then there are two situations:

1) If the client each time the production of more water, that is, we often say that the client to the larger package, TCP This porter will be carried out several times to carry.

2) If the client produces less water each time, TCP may wait for the client to produce multiple times, and then transport all the water to the other end.


In the first case, it is necessary for us to carry on the sticky packet, at the other end of the receiving time, we need to stick together the results of multiple acquisition, we can understand the information, the second case, we receive at the other end of the time, we must do the unpacking process, because each time the information received, may be another remote side of the packet sent Being stuck together by TCP.


We do both of these scenarios to give a specific scenario:

1) A single send packet content too much, the phenomenon of unpacking:

Let's write the client's bootstrap first:

Package Com.lyncc.netty.stickpackage.myself;import Io.netty.bootstrap.bootstrap;import Io.netty.channel.channelfuture;import Io.netty.channel.channelinitializer;import io.netty.channel.ChannelOption; Import Io.netty.channel.channelpipeline;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.linebasedframedecoder;import Io.netty.handler.codec.string.stringdecoder;public class Baseclient {static final string HOST = System.getproperty    ("Host", "127.0.0.1");    static final int PORT = Integer.parseint (System.getproperty ("PORT", "8080"));    static final int SIZE = Integer.parseint (System.getproperty ("SIZE", "256"));        public static void Main (string[] args) throws Exception {Eventloopgroup group = new Nioeventloopgroup ();            try {Bootstrap b = new Bootstrap (); B.group (group) ChanNel (niosocketchannel.class). Option (Channeloption.tcp_nodelay,true). Handler (New Channelinitialize R<socketchannel> () {@Override public void Initchannel (Socketchannel ch) throws Exce ption {Channelpipeline p = ch.pipeline ();//P.addlast (New Linebasedframedecoder (1                     024));                     P.addlast (New Stringdecoder ());                 P.addlast (New Baseclienthandler ());            }             });            Channelfuture future = B.connect (HOST, PORT). sync ();            Future.channel (). Writeandflush ("Hello Netty Server, I am a common client");        Future.channel (). Closefuture (). sync ();        } finally {group.shutdowngracefully (); }    }}
Client's handler:

Package Com.lyncc.netty.stickpackage.myself;import Io.netty.buffer.bytebuf;import Io.netty.buffer.unpooled;import Io.netty.channel.channelhandlercontext;import Io.netty.channel.channelinboundhandleradapter;public Class Baseclienthandler extends channelinboundhandleradapter{        private byte[] req;         Private int counter;        public Baseclienthandler () {//        req = ("BAZINGALYNCC is learner" + System.getproperty ("Line.separator"))//           . GetBytes ();        req = ("In this chapter your general, we recommend Java Concurrency I n Practice by Brian Goetz. His book w "                +" ill give We ' ve reached an exciting point-in the next chapter we ' ll discuss bootstrapping, the process "                + "of configuring and Connecting all of Netty's components to bring your learned on threading models in GE "     &nbs p;          + "neral and Netty ' s threading model in particular, whose Performance and consistency Advantages we discuss "                 + "ed in detail in the chapter you general, we recommend Java Concurrency in practice by B Rian Goetz. Hi "                +" s book would give We ' ve reached an exciting point-in the next chapter we ' ll discuss bootstrapping, the '                  + "Process of configuring and connecting all of Netty ' s component s to bring your learned about threading "                + "models in general and Netty ' s Threading model in particular, whose performance and consistency Advantag "       &  nbsp;        + "Es we discussed in Detailin this chapter your general, we recommend Java Concurrency in practice by Bri "                 + "an Goetz. His book would give We ' ve reached an exciting point-in the next chapter;the counter is:1 2222 "    &nbs p;           + "Sdsa ddasd asdsadas Dsadasdas"). GetBytes ();    }        @Override     public void channelactive ( Channelhandlercontext ctx) throws Exception {        bytebuf message = null;//         for (int i = 0; I < 100; i++) {//            message = Unpooled.buffer (req.length); /            message.writebytes (req);//             ctx.writeandflush (message);//        }        message = Unpooled.buffer (req.length);         message.writebytes (req);        Ctx.writeandflush (message);        message = Unpooled.buffer (req.length);         message.writebytes (req);        Ctx.writeandflush (message);   }        @Override     public void Channelread (Channelhandlercontext ctx, Object msg)         throws ExCeption {        String buf = (string) msg;         SYSTEM.OUT.PRINTLN ("Now is:" + buf + "; The counter is: "+ ++counter);   }    @Override     public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {        ctx.close () ;   }        }
Serverbootstrap on the service side:

Package Com.lyncc.netty.stickpackage.myself;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;import Io.netty.handler.codec.string.stringdecoder;import Java.net.inetsocketaddress;public class BaseServer {private int        Port    public baseserver (int port) {this.port = port;        } public void Start () {Eventloopgroup bossgroup = new Nioeventloopgroup (1);        Eventloopgroup Workergroup = new Nioeventloopgroup (); try {serverbootstrap SBS = new Serverbootstrap (). Group (Bossgroup,workergroup). Channel (NIOSERVERSOCKETCHANNEL.C Lass). LocalAddress (New inetsocketaddress (port)). Childhandler (New CHANNELINITIALIZER&LT;SOCKETCHANNEL&G  t; () {                                              protected void Initchannel (Socketchannel ch) throws Exception {//                            Ch.pipeline (). AddLast (New Linebasedframedecoder (1024));                            Ch.pipeline (). AddLast (New Stringdecoder ());                        Ch.pipeline (). AddLast (New Baseserverhandler ());                                            };             }). Option (Channeloption.so_backlog, $). Childoption (Channeloption.so_keepalive, true);                            Bind port, start receiving incoming connections channelfuture future = Sbs.bind (port). sync ();             System.out.println ("Server start listen at" + port);        Future.channel (). Closefuture (). sync ();            } catch (Exception e) {bossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully ();        }} public static void Main (string[] args) throws Exception {int port;           if (Args.length > 0) { Port = Integer.parseint (Args[0]);        } else {port = 8080;    } new Baseserver (port). Start (); }}
Handler on the service side:

Package Com.lyncc.netty.stickpackage.myself;import Io.netty.channel.channelhandlercontext;import Io.netty.channel.channelinboundhandleradapter;public class Baseserverhandler extends channelinboundhandleradapter{            private int counter;            @Override public    void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {                string body = (string ) msg;        SYSTEM.OUT.PRINTLN ("Server Receive order:" + body + "; The counter is:" + ++counter);    }            @Override public    void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {        Cause.printstacktrace ();        Ctx.close ();    }}

As usual, we run the server side first:

We run the client again, after the client starts, we look at the server side of the console printout:

We can see the server side three times received two times the client sent the long message


2) A single send packet content too much situation, sticky packet phenomenon:

The client and server bootstrap do not change, we modify the Channelactive code that the client sends the message:

Package Com.lyncc.netty.stickpackage.myself;import Io.netty.buffer.bytebuf;import Io.netty.buffer.unpooled;import Io.netty.channel.channelhandlercontext;import Io.netty.channel.channelinboundhandleradapter;public Class        Baseclienthandler extends channelinboundhandleradapter{private byte[] req;        private int counter; Public Baseclienthandler () {req = ("BAZINGALYNCC is Learner"). GetBytes ();//req = ("In the chapter you Gen eral, we recommend Java Concurrency in practice by Brian Goetz. His book W "//+" Ill give we ' ve reached an exciting point-in the next Chapter We ' ll discuss bootstrapping, The process "//+" of configuring and connecting all of Netty ' s components to bring your learned about Thre  Ading models in GE "//+" neral and Netty ' s threading model in particular, whose performance and consistency Advantages we discuss "//+" ed in detail in this chapter your general, we recommend Java ConcurrEncy in practice by Brian Goetz. Hi "//+" s book would give we ' ve reached an exciting point-in the next Chapter We ' ll discuss bootstrapping, The "//+" process of configuring and connecting all of Netty's components to bring your learned about Thre  Ading "//+" models in general and Netty's threading model in particular, whose performance and consistency Advantag "//+" Es we discussed in Detailin this chapter your general, we recommend Java Concurrency in Prac Tice by Bri '//+ ' an Goetz. His book would give We ' ve reached an exciting point-in the next chapter;the counter is:1 2222 "//+" SDSA DD    ASD Asdsadas Dsadasdas "). GetBytes (); } @Override public void channelactive (Channelhandlercontext ctx) throws Exception {Bytebuf message = nul        L            for (int i = 0; i < i++) {message = Unpooled.buffer (req.length);            Message.writebytes (req); Ctx.writeaNdflush (message);         }//message = Unpooled.buffer (req.length);//Message.writebytes (req);//Ctx.writeandflush (message);//    Message = Unpooled.buffer (req.length);//Message.writebytes (req);//Ctx.writeandflush (message);    } @Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {ctx.close (); }}
We start the server side again:


After you start the client, you still see the server-side console:

As can be seen, the client sends 100 times of information, by the server side three times to receive, this happens sticky packet phenomenon


The above is the typical adhesive and unpacking scenarios

Learn Netty (vi) The TCP Sticky pack unpacking scenario

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.