Netty学习之路(五)-TCP粘包/拆包问题

TCP是个“流协议”,所谓流,就是没有界限的一串数据。TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行包的划分,所以一个完整的包可能会被TCP拆分成多个包进行发送,也有可能吧多个小的包封装成一个大的数据包发送,这就是TCP粘包和拆包问题。

TCP粘包/拆包产生情况

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

TCP粘包/拆包发生的原因

  1. 应用程序write写入的字节大小大于套接字借口发送缓冲区大小
  2. 进行MSS大小的TCP分段
  3. 以太网帧的payload大于MTU进行IP分片

解决策略

  1. 消息定长,例如每个报文的大小为固定长度200字节,如果不够,空位补空格
  2. 在包尾增加回车换行符进行分割,例如FTP协议
  3. 将消息分为消息头和消息体,消息头中包含表示信息总长度的字段
  4. 更复杂的应用层协议

发生TCP粘包编码实践

服务端

每读到一条消息后,就计一次数,然后发送应答消息给客户端。

package com.ph.Netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Create by PH on 2018/11/5
 */
public class NettyServer {

    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 e) {
                //采用默认值
            }
        }
        new NettyServer().bind(port);
    }

    public void bind(int port) throws Exception{
        //NioEventLoopGroup是一个线程组,包含了一组NIO线程,专门用于网络事件的处理,实际上他们就是Reactor线程组
        //bossGroup仅接收客户端连接,不做复杂的逻辑处理,为了尽可能减少资源的占用,取值越小越好
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //用于进行SocketChannel的网络读写
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
            ServerBootstrap b = new ServerBootstrap();
            //配置NIO服务端
            b.group(bossGroup, workerGroup)
                    //指定使用NioServerSocketChannel产生一个Channel用来接收连接,他的功能对应于JDK
                    // NIO类库中的ServerSocketChannel类。
                    .channel(NioServerSocketChannel.class)
                    //BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,
                    // 用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,
                    // Java将使用默认值50。
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //绑定I/O事件处理类,作用类似于Reactor模式中的Handler类,主要用于处理网络I/O事件
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel arg0) throws Exception {
                            arg0.pipeline().addLast(new ServerHandler());
                        }

                    });
            //绑定端口,同步等待绑定操作完成,完成后返回一个ChannelFuture,用于异步操作的通知回调
            ChannelFuture f = b.bind(port).sync();
            //等待服务端监听端口关闭之后才退出main函数
            f.channel().closeFuture().sync();
        } finally {
            //退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

/**
 * ChannelInboundHandlerAdapter实现自ChannelInboundHandler
 * ChannelInboundHandler提供了不同的事件处理方法你可以重写
 */
class ServerHandler extends ChannelInboundHandlerAdapter {

    private int count = 0;

    /**
     * 接受客户端发送的消息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //类似JDK中的ByteBuffer对象,不过它提供了更加强大和灵活的功能
        ByteBuf buf = (ByteBuf) msg;
        //通过readableBytes()方法获取缓冲区可读的字节数
        byte[] req = new byte[buf.readableBytes()];
        //将缓冲区中的字节数组复制到新建的byte数组中
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println("Server receive: " + body);
        //获得ByteBuf类型的数据
        ByteBuf resp = Unpooled.copiedBuffer(("Server message "+String.valueOf(++count)).getBytes());
        //向客户端发送消息,不直接将消息写入SocketChannel中,只是把待发送的消息放到发送缓存数组中,
        //再通过调用flush方法将缓冲区中的消息全部写到SocketChannel中
        ctx.write(resp);
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将消息发送队列中的消息写入到SocketChannel中发送给对方
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //当发生异常时释放资源
        ctx.close();
    }
}

客户端

客户端每接收到服务端一条应答消息之后就打印一次计数器,按照设计,客户端应该打印100次服务端的消息

package com.ph.Netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Create by PH on 2018/11/5
 */
public class NettyClient {

    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 e) {
                //采用默认值
            }
        }
        new NettyClient().connect(port, "127.0.0.1");
    }

    public void connect(int port, String host) throws  Exception{
        //配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        public void initChannel(SocketChannel ch) throws Exception{
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });
            //发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();
            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}

class ClientHandler extends ChannelInboundHandlerAdapter {

    private  ByteBuf msg;
    private int count = 0;
    private byte[] req;

    public ClientHandler() {
        req = ("Client message"+System.getProperty("line.separator")).getBytes();
    }

    /**
     * 当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用此方法
     * @param ctx
     */
    public void channelActive(ChannelHandlerContext ctx) {
        //发送消息到服务端
        for (int i=0;i<100;i++) {
            msg = Unpooled.buffer(req.length);
            msg.writeBytes(req);
            ctx.writeAndFlush(msg);
        }
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "utf-8");
        System.out.println("Client receive :" + body + "the counter is:" + String.valueOf(++count));
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}

运行结果

  • 服务端:

    Server receive: Client message…(省略57条)Client message
    Server receive: Client message…(省略43条)Client message
    收到两条消息,发生TCP粘包

  • 客户端:

    Client receive :Server message Server message the counter is:1
    收到一条消息,而按照设计,客户端应该收到100条消息。因为服务端只收到了2条消息,所以服务端实际上只发送了2条应答,说明服务端返回的应答消息也发生了粘包

利用LineBasedFrameDecoder解决TCP粘包问题

LineBasedFrameDecoder的工作原理是它依次遍历ByteBuf中的可读字节,判读是否有“\n”或者“\r\n”,如果有,就以此位置为结束位置,从可读索引到结束位置区间的字节就组成了一行。它是以换行符为结束标志的解码器,支持携带结束符或者不携带结束符两种解码方式,同时支持配置单行的最大长度。如果连续读取到最大长度后仍然没有发现换行符,就会抛出异常,同时忽略掉之前读到的异常码流。
StringDecoder就是将接受到的对象转换成字符串,然后继续调用后面的Handler.LineBasedFrameDecoder+StringDecoder组合就是按行切换的文本解码器。

服务端

package com.ph.Netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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;

/**
 * Create by PH on 2018/11/3
 */
public class NettyServer {

    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 e) {
                //采用默认值
            }
        }
        new NettyServer().bind(port);
    }

    public void bind(int port) throws Exception{
        //NioEventLoopGroup是一个线程组,包含了一组NIO线程,专门用于网络事件的处理,实际上他们就是Reactor线程组
        //bossGroup仅接收客户端连接,不做复杂的逻辑处理,为了尽可能减少资源的占用,取值越小越好
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //用于进行SocketChannel的网络读写
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
            ServerBootstrap b = new ServerBootstrap();
            //配置NIO服务端
            b.group(bossGroup, workerGroup)
                    //指定使用NioServerSocketChannel产生一个Channel用来接收连接,他的功能对应于JDK
                    // NIO类库中的ServerSocketChannel类。
                    .channel(NioServerSocketChannel.class)
                    //BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,
                    // 用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,
                    // Java将使用默认值50。
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //绑定I/O事件处理类,作用类似于Reactor模式中的Handler类,主要用于处理网络I/O事件
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel arg0) throws Exception {
                            arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            arg0.pipeline().addLast(new StringDecoder());
                            arg0.pipeline().addLast(new ServerHandler());
                        }

                    });
            //绑定端口,同步等待绑定操作完成,完成后返回一个ChannelFuture,用于异步操作的通知回调
            ChannelFuture f = b.bind(port).sync();
            //等待服务端监听端口关闭之后才退出main函数
            f.channel().closeFuture().sync();
        } finally {
            //退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

/**
 * ChannelInboundHandlerAdapter实现自ChannelInboundHandler
 * ChannelInboundHandler提供了不同的事件处理方法你可以重写
 */
class ServerHandler extends ChannelInboundHandlerAdapter {

    private int count = 0;

    /**
     * 接受客户端发送的消息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //拿到的msg已经是解码成字符串之后的应答消息了
        String body = (String)msg;
        ++count;
        System.out.println("Server receive: " + body + count);
        //获得ByteBuf类型的数据
        ByteBuf resp = Unpooled.copiedBuffer(("Server message: "+System.getProperty("line.separator")).getBytes());
        //向客户端发送消息,不直接将消息写入SocketChannel中,只是把待发送的消息放到发送缓存数组中,
        //再通过调用flush方法将缓冲区中的消息全部写到SocketChannel中
        ctx.write(resp);
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将消息发送队列中的消息写入到SocketChannel中发送给对方
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //当发生异常时释放资源
        ctx.close();
    }
}

客户端

package com.ph.Netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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;

/**
 * Create by PH on 2018/11/3
 */
public class NettyClient {

    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 e) {
                //采用默认值
            }
        }
        new NettyClient().connect(port, "127.0.0.1");
    }

    public void connect(int port, String host) throws  Exception{
        //配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        public void initChannel(SocketChannel ch) throws Exception{
                            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });
            //发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();
            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}

class ClientHandler extends ChannelInboundHandlerAdapter {

    private  ByteBuf msg;
    private int count = 0;
    private byte[] req;

    public ClientHandler() {
        req = ("Client message "+System.getProperty("line.separator")).getBytes();
    }

    /**
     * 当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用此方法
     * @param ctx
     */
    public void channelActive(ChannelHandlerContext ctx) {
        //发送消息到服务端
        for (int i=0;i<100;i++) {
            msg = Unpooled.buffer(req.length);
            msg.writeBytes(req);
            ctx.writeAndFlush(msg);
        }
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        **//拿到的msg已经是解码成字符串之后的应答消息了。**
        String body = (String)msg;
        System.out.println("Client receive :" + body + ", the counter is:" + String.valueOf(++count));
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}

运行结果

服务端:

Server receive: Client message 1
Server receive: Client message 2
Server receive: Client message 3
......
Server receive: Client message 100

客户端:

Client receive :Server message: , the counter is:1
Client receive :Server message: , the counter is:2
Client receive :Server message: , the counter is:3
......
Client receive :Server message: , the counter is:100

猜你喜欢

转载自blog.csdn.net/PH15045125/article/details/83755171