Netty (三) TCP粘包和拆包解决方案

来源:互联网 发布:泊众棋牌五星红辉源码 编辑:程序博客网 时间:2024/05/18 03:53

tcp是一个“流”的协议,一个完整的包可能会被TCP拆分成多个包进行发送,也可能把小的封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。

粘包、拆包问题说明

假设客户端分别发送数据包D1和D2给服务端,由于服务端一次性读取到的字节数是不确定的,所以可能存在以下4种情况。

  • 1.服务端分2次读取到了两个独立的包,分别是D1,D2,没有粘包和拆包;
  • 2.服务端一次性接收了两个包,D1和D2粘在一起了,被成为TCP粘包;
  • 3.服务端分2次读取到了两个数据包,第一次读取到了完整的D1和D2包的部分内容,第二次读取到了D2包的剩余内容,这被称为拆包;
  • 4.服务端分2次读取到了两个数据包,第一次读取到了部分D1,第二次读取D1剩余的部分和完整的D2包;

如果此时服务端TCP接收滑动窗非常小,而数据包D1和D2都很大,很有可能发送第五种可能,即服务端多次才能把D1和D2接收完全,期间多次发生拆包情况。(TCP接收滑动窗:是接收端的大小,随着流量大小而变化,如果我的解释还不明确,请读者自行百度,或者查阅《计算机网络》、《TCP/IP》中TCP的内容)

粘包问题的解决策略

由于底层的TCP无法理解上层的业务逻辑,所以在底层是无法确保数据包不被拆分和重组的,这个问题只能通过上层的应用协议栈设计来解决,根据业界的主流协议的解决方案,归纳如下:

  • 1.消息定长,例如每个报文的大小为固定长度200字节,如果不够,空位补空格;
  • 2.在包尾增加回车换行符进行分割,例如FTP协议;
  • 3.将消息分为消息头和消息体,消息头中包含表示消息总长度(或者消息体长度)的字段,通常设计思路是消息头的第一个字段用int来表示消息的总长度;(我之前linux C开发,就用的这种)。
  • 4.更复杂的应用层协议;

 

为了解决TCP粘包拆包的问题,Netty默认提供了多种编码器来处理,以下通过代码来说明;

服务端:

TimeServer.java

package nettytest.tcppackage;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.LineBasedFrameDecoder;import io.netty.handler.codec.string.StringDecoder;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 时间服务器, 粘包拆包初步解决:LineBasedFrameDecoder通过标识符号哦换行符 * Created by Lovell on 30/09/2016. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class TimeServer {    private static Logger logger = LoggerFactory.getLogger(TimeServer.class);    public void bind(int port) throws Exception {        // 配置服务端的NIO线程组        // NioEventLoopGroup类是个线程组,包含一组NIO线程,用于网络事件的处理        // (实际上他就是Reactor 线程组)        // 创建2个线程组, 1个是服务端接收客户端的连接,        // 另一个是进行SocketChannel的网络读写        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            // ServerBootstrap 类, 是启动NIO服务器的辅助启动类            ServerBootstrap serverBootstrap = new ServerBootstrap();            serverBootstrap.group(bossGroup, workerGroup)                    .channel(NioServerSocketChannel.class)  // NIO Socket管道                    .option(ChannelOption.SO_BACKLOG, 1024) // 握手成功缓存大小                    .option(ChannelOption.SO_KEEPALIVE, true) // 2小时无数据激活心跳机制                    .childHandler(new ServerChannelHandler());            /**             * 这个都是socket的标准参数,并不是netty自己的。             * 具体为:             * ChannelOption.SO_BACKLOG, 1024             * BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度。             * 如果未设置或所设置的值小于1,Java将使用默认值50。             * ChannelOption.SO_KEEPALIVE, true             * 是否启用心跳保活机制。在双方TCP套接字建立连接后(即都进入ESTABLISHED状态)并且在两个小时左右上层没有任何数据传输的情况下,             * 这套机制才会被激活。             * ChannelOption.TCP_NODELAY, true             * 在TCP/IP协议中,无论发送多少数据,总是要在数据前面加上协议头,同时,对方接收到数据,也需要发送ACK表示确认。             * 为了尽可能的利用网络带宽,TCP总是希望尽可能的发送足够大的数据。             * 这里就涉及到一个名为Nagle的算法,该算法的目的就是为了尽可能发送大块数据,避免网络中充斥着许多小数据块。             * TCP_NODELAY就是用于启用或关于Nagle算法。如果要求高实时性,有数据发送时就马上发送,就将该选项设置为true关闭Nagle算法;             * 如果要减少发送次数减少网络交互,就设置为false等累积一定大小后再发送。默认为false。             */            // 绑定端口,同步等待成功            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();            // 等待服务端监听端口关闭            channelFuture.channel().closeFuture().sync();        } finally {            // 释放线程池资源            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }    private class ServerChannelHandler extends ChannelInitializer<SocketChannel> {        @Override        protected void initChannel(SocketChannel ch) throws Exception {            // 为了解决TCP粘包拆包的问题,Netty默认提供了多种编码器来处理,以下通过代码来说明;            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));            ch.pipeline().addLast(new StringDecoder());            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(args[0]);            } catch (NumberFormatException ex) {            }        }        new TimeServer().bind(port);    }}
TimeServerHandler.java

package nettytest.tcppackage;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.Date;/** * Created by Lovell on 30/09/2016. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class TimeServerHandler extends SimpleChannelInboundHandler {    private static Logger logger = LoggerFactory.getLogger(TimeServerHandler.class);    private int counter;    // 用于网络的读写操作    @Override    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {        String body = (String)msg;        System.out.println("the time server order : " + body + ", the counter is :" + (++counter));        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)?new Date(                           System.currentTimeMillis()).toString():"BAD ORDER";        currentTime +=System.getProperty("line.separator");   // System.getProperty("line.separator"),获取/n的作用        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());        ctx.writeAndFlush(resp);        // 当客户端和服务端建立tcp成功之后,Netty的NIO线程会调用channelActive        // 发送查询时间的指令给服务端。        // 调用ChannelHandlerContext的writeAndFlush方法,将请求消息发送给服务端        // 当服务端应答时,channelRead方法被调用    }    @Override    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {        ctx.flush();        // 它的作用是把消息发送队列中的消息写入SocketChannel中发送给对方        // 为了防止频繁的唤醒Selector进行消息发送,Netty的write方法,并不直接将消息写入SocketChannel中        // 调用write方法只是把待发送的消息发到缓冲区中,再调用flush,将发送缓冲区中的消息        // 全部写到SocketChannel中    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {        super.exceptionCaught(ctx, cause);        ctx.close();    }}
客户端:

TimeClient.java

package nettytest.tcppackage;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;import io.netty.handler.codec.LineBasedFrameDecoder;import io.netty.handler.codec.string.StringDecoder;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Created by Lovell on 30/09/2016. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class TimeClient {    private static Logger logger = LoggerFactory.getLogger(TimeClient.class);    public void connect(String host,int port)throws Exception{        // 配置服务端的NIO线程组        EventLoopGroup group = new NioEventLoopGroup();        try {            // Bootstrap 类,是启动NIO服务器的辅助启动类            Bootstrap b = new Bootstrap();            b.group(group).channel(NioSocketChannel.class)                    .option(ChannelOption.TCP_NODELAY,true)                    .handler(new ChannelInitializer<SocketChannel>() {                        @Override                        public void initChannel(SocketChannel ch)                                throws Exception{                            // 增加 LineBasedFrameDecoder 和 StringDecoder 编码器                            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));                            ch.pipeline().addLast(new StringDecoder());                            ch.pipeline().addLast(new TimeClientHandler());                        }                    });            // 发起异步连接操作            ChannelFuture f= b.connect(host,port).sync();            // 等待客服端链路关闭            f.channel().closeFuture().sync();        } finally {            group.shutdownGracefully();        }    }    public static void main(String[]args)throws Exception{        int port = 8080;        if(args!=null && args.length>0){            try {                port = Integer.valueOf(args[0]);            }            catch (NumberFormatException ex){}        }        new TimeClient().connect("127.0.0.1",port);    }}
TimeClientHandler.java

package nettytest.tcppackage;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Created by Lovell on 30/09/2016. *//* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@  @@@@@@@@        @@  @@@@@@@  @@        @@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@  @@@@@  @@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@  @@@  @@@@       @@@  @@@@@@@@@  @@@@@@@@@@ @@@@  @@@@@@@@  @@@@  @@@@@  @  @@@@@  @@@@@@@@  @@@@@@@@@  @@@@@@@@@@ @@@@        @@        @@@@@@   @@@@@@        @@        @@@        @@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */public class TimeClientHandler extends SimpleChannelInboundHandler{    private static Logger logger = LoggerFactory.getLogger(TimeClientHandler.class);    // 写日志    private int counter;    private byte[] req;    public TimeClientHandler(){        req = ("QUERY TIME ORDER"+System.getProperty("line.separator")).getBytes();    }    @Override    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {        String body = (String)msg;        System.out.println("Now is : " + body+", the countor is : "+ ++counter);     }    @Override    public void channelActive(ChannelHandlerContext ctx){        // 当客户端和服务端建立tcp成功之后,Netty的NIO线程会调用channelActive        // 发送查询时间的指令给服务端。        // 调用ChannelHandlerContext的writeAndFlush方法,将请求消息发送给服务端        // 当服务端应答时,channelRead方法被调用        ByteBuf firstMessage;        for (int i = 0; i < 100; i++) {            firstMessage = Unpooled.buffer(req.length);            firstMessage.writeBytes(req);            ctx.writeAndFlush(firstMessage);        }    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){        logger.warn("message from:"+cause.getMessage());        ctx.close();    }}

以上的代码,主要就是增加 LineBasedFrameDecoder 和StringDecoder编码器来处理粘包、拆包问题。全部项目代码,源码在src/main/java/NettyStickyPacket下,分为客户端和服务端,他们的代码基本和Netty入门章节的代码类似,只是增加了解码器。

 

LineBasedFrameDecoder 和StringDecoder编码器说明

LineBasedFrameDecoder 工作原理:依次编译bytebuf中的可读字符,判断看是否有“\n”或者“\r\n”,如果有,就以此位置为结束位置,从可读索引到结束位置区间的字节就组成了一行。它是以换行符为结束标志的解码器,支持携带结束符或者不携带结束符两种解码方式,同时支持单行的最大长度。如果连续读取到最大长度后,仍然没有发现换行符,就会抛出异常,同时忽略掉之前读到的异常码流。

StringDecoder功能:将接收到的对象转成字符串,然后继续调用后面的handler。 LineBasedFrameDecoder + StringDecoder组成就是按行切换的文本解码器,它被设计用来支持TCP的粘包和拆包。

可能读者会提出新的疑问:如果发送的消息不是以换行符结束怎么办?或者没有回车换行符,靠消息头中的长度字段来分包怎么办?是不是需要自己写半包解码器?答案是否定的,Netty提供了多种支持TCP粘包/拆包的解码器。

关于“分隔符解码器”,下一章单独讲解说明。

 

源码下载

GitHub地址:https://github.com/orange1438/Netty_Course

 
作者:orange1438出处:http://www.cnblogs.com/orange1438/本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
来自:http://www.cnblogs.com/orange1438/p/5009769.html
0 0
原创粉丝点击