Example and analysis of TCP sticky packet problem code in Netty

Source: Internet
Author: User
Tags ord

[TOC]

Example of TCP sticky problem code in Netty

Netty will occur in the TCP sticky packet and unpacking problems, of course, in fact, for the former network engineer, the first time to see this noun may be a bit uncomfortable, because in that we are talking about TCP cumulative send and Shard function, but the truth is the same.
The code comes from the 4th chapter of the Netty authoritative guide, but I still make some changes to some of the code, the reason or the Netty version of the problem, the book is Netty 5.x version, the official has abandoned this version, I use the official 4.x version.

It should be noted that the code is also the code of the time server, but I have a lot of basic comments are removed, because in this time, in fact, the basic use of Netty should be familiar.

In addition, I also added in the Timeclienthandler.java code for the TCP sticky packet problem basic analysis, of course, can also be a reference book description.

Service-Side Timeserver.java
Package Cn.xpleaf.netty;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;public class Timeserver {public void bind (int port) throws Exceptio        n {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 Childchannelhandler ());            Channelfuture f = b.bind (port). sync ();        F.channel (). Closefuture (). sync (); } finally {bossgroup.shutdowngracefully ();            Workergroup.shutdowngracefully (); }} Private class Childchannelhandler extends Channelinitializer<socketchannel> {@Override prot        ected void Initchannel (Socketchannel ch) throws Exception {Ch.pipeline (). AddLast (New Timeserverhandler ());        }} 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 Timeserver (    ). bind (port); }}
Timeserverhandler.java
Package Cn.xpleaf.netty;import Java.sql.date;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 Timeserverhandler extends Channelinboundhandleradapter {    private int counter = 0; @Override public void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {bytebuf buf = (byteb        UF) msg;        byte[] req = new byte[buf.readablebytes ()];        Buf.readbytes (req); Remove newline character String BODY = new String (req, "Utf-8"). Substring (0, Req.length-system.getproperty ("line.        Separator "). Length ()); The role of counter is to mark the number of times a client has received a request System.out.println ("The time server receive order:" + body + ";        The counter is: "+ ++counter);                 String currenttime = "QUERY time ORDER". Equalsignorecase (body)? New Date (System.currenttimemillis ()). ToString (): "BAD ORDER ";        CurrentTime = currenttime + system.getproperty ("Line.separator");        Bytebuf resp = Unpooled.copiedbuffer (Currenttime.getbytes ());    Ctx.write (RESP);    } @Override public void Channelreadcomplete (Channelhandlercontext ctx) throws Exception {Ctx.flush ();    } @Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {ctx.close (); }}
Client Timeclient.java
Package Cn.xpleaf.netty;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;public class Timeclient {public void connect (int port, String host) throw        s Exception {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 Initch                    Annel (Socketchannel ch) throws Exception {Ch.pipeline (). AddLast (New Timeclienthandler ());            }                }); Channelfuture f =B.connect (host, port). sync ();        F.channel (). Closefuture (). sync ();        } finally {//gracefully exits, releasing the 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 Timeclient (). Connect (Port, "    localhost "); }}
Timeclienthandler.java
Package Cn.xpleaf.netty;import Java.util.logging.logger;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 Timeclienthandler extends Channelinboundhandleradapter {private static final Logger Logger = Logger.getlogger (TimeServ    ErHandler.class.getName ());    private int counter;    Private byte[] req;    Public Timeclienthandler () {req = ("QUERY time ORDER" + system.getproperty ("Line.separator")). GetBytes ();        } @Override public void channelactive (Channelhandlercontext ctx) {BYTEBUF message = NULL; /** * Intent is to send 100 messages to the server, according to the design should be received servers * 100 responses, but due to the TCP sticky packet problem, not every message will be sent separately, * TCP itself mechanism will make the message reached a certain length before sending out Go, so the actual test situation is: * TCP sent only two data, and 100 messages are sent out in two parts, instead of each message * sent separately, there is a so-called sticky packet problem, and the service side in the response, it is obviously likely not to be * back two times Packet, because the reason is the same, the server side of TCP will also be Netty two times sent data into a * packet intoLine send, of course, which involves the knowledge of TCP, can refer to TCP/IP Volume 1 */for (int i = 0; i < i++) {message = Unpooled.buff            ER (req.length);            Message.writebytes (req);        Ctx.writeandflush (message); }} @Override public void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {Bytebuf bu        f = (bytebuf) msg;        byte[] req = new byte[buf.readablebytes ()];        Buf.readbytes (req);        String BODY = new String (req, "utf-8"); Counter's role is to mark this as the number of times a client request is received SYSTEM.OUT.PRINTLN ("Now is:" + body + ";    The counter is: "+ ++counter); } @Override public void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {Logger        . Warning ("Unexpected exception from downstream:");    Ctx.close (); }}
Test service-Side run results
The time server receive Order:query time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquer Y Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time ORD Erquery Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery TI ME orderquery Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderqu ERY Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time O Rderquery Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time ORDER QUERY time Orderque; ThE counter is:1the time server receive order:y time Orderquery time Orderquery time Orderquery time Orderquery time ORD Erquery Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery TI ME orderquery Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderqu ERY Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time O Rderquery Time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery time Orderquery Time Orderquery time Orderquery time Orderquery time Orderquery time ORDER; The Counter Is:2
Client Run Results
Now is : BAD ORDERBAD ORDER ; the counter is : 1

From the above results, the problem of TCP sticky packets is obvious.

Example and analysis of TCP sticky packet problem code in Netty

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.