Netty——ReplayingDecoder+自定义协议解决TCP粘包、拆包

一、TCP 粘包和拆包基本介绍

TCP是面向连接的,面向流的,提供高可靠性服务。收发两端(客户端和服务器端)都要有一一成对的socket,因此,发送端为了将多个发给接收端的包,更有效的发给对方,使用了优化方法(Nagle算法),将多次间隔较小且数据量小的数据,合并成一个大的数据块,然后进行封包。这样做虽然提高了效率,但是接收端就难于分辨出完整的数据包了,因为面向流的通信是无消息保护边界的。

由于TCP无消息保护边界, 需要在接收端处理消息边界问题,也就是我们所说的粘包、拆包问题。

TCP粘包、拆包图解

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

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

特别要注意的是,如果TCP的接受滑窗非常小,而数据包D1和D2比较大,很有可能会发生第五种情况,即服务端分多次才能将D1和D2包完全接受,期间发生多次拆包。

二、解决TCP粘包、拆包问题

解决问题的根本手段就是找出消息的边界。

Netty提供了以下三种方式解决TCP粘包和拆包问题:

  • DelimiterBasedFrameDecoder:分隔符。
  • LineBasedFrameDecoder:结束符\n。
  • FixedLengthFrameDecoder:固定长度。
  • LengthFieldBasedFrameDecoder+LengthFieldPrepender:自定义消息长度。
  • ReplayingDecoder:自定义协议。

三、ReplayingDecoder+自定义协议解决TCP粘包、拆包

3.1、自定义协议,数据包格式

自定义协议
数据包格式
+--------+--------+----------+ 
|  Type  | Length |  Content | 
+--------+--------+----------+ 
1.Type:消息类型,为int类型的数据,1、表示文本消息,2表示图片消息,3表示视频消息等
2.Length:传输数据的长度,int类型
3.content:要传输的数据

协议实体的定义

/**
 * 自定义协议
 * 数据包格式
 * +--------+--------+----------+
 * |  Type  | Length |  Content |
 * +--------+--------+----------+
 * 1.Type:消息类型,为int类型的数据,1、表示文本消息,2表示图片消息,3表示视频消息等
 * 2.Length:传输数据的长度,int类型
 * 3.content:要传输的数据
 */
public class MessageProtocol {

    /**
     * 消息类型type,默认为文本消息
     */
    private int type = 1;

    /**
     * 消息长度length
     */
    private int length;

    /**
     * 消息的内容
     */
    private byte[] content;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public byte[] getContent() {
        return content;
    }

    public void setContent(byte[] content) {
        this.content = content;
    }
}

3.2、MessageProtocolDecoder解码器

public class MessageProtocolDecoder extends ReplayingDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List list) throws Exception {
        System.out.println("MessageProtocolDecoder.decode 被调用");
        //将二进制字节码 --> MessageProtocol 数据包(对象)
        int messageType = in.readInt();
        int length = in.readInt();
        byte[] content = new byte[length];
        in.readBytes(content);

        //封装成MessageProtocol 对象,放入list传递给下一个handler
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setType(messageType);
        messageProtocol.setLength(length);
        messageProtocol.setContent(content);
        list.add(messageProtocol);
    }
}

3.3、MessageProtocolEncoder编码器

public class MessageProtocolEncoder extends MessageToByteEncoder {

    @Override
    protected void encode(ChannelHandlerContext ctx, MessageProtocol msg, ByteBuf out) throws Exception {
        System.out.println("MessageProtocolEncoder.encode 被调用");
        out.writeInt(msg.getType());
        out.writeInt(msg.getLength());
        out.writeBytes(msg.getContent());
    }
}

3.4、服务端的实现

public class TcpServer {

    private int port;

    public TcpServer(int port){
        this.port = port;
    }

    //编写run方法处理客户端请求
    public void run(){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(8);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new TcpServerInitializer());

            System.out.println("netty 服务器启动!");
            ChannelFuture channelFuture = bootstrap.bind(port).sync();

            //监听关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new TcpServer(7000).run();
    }
}

3.5、服务端Initializer

public class TcpServerInitializer extends ChannelInitializer {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //获取到pipeline
        ChannelPipeline pipeline = socketChannel.pipeline();

        //解码器
        pipeline.addLast("MessageProtocolDecoder",new MessageProtocolDecoder());

        //编码器
        pipeline.addLast("MessageProtocolEncoder",new MessageProtocolEncoder());

        //加入业务处理的handler
        pipeline.addLast("handler",new TcpServerHandler());
    }
}

3.6、服务端Handler

public class TcpServerHandler extends SimpleChannelInboundHandler {

    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        //接收到数据并处理
        int messageType = msg.getType();
        int length = msg.getLength();
        byte[] content = msg.getContent();
        System.out.println("服务器端接收到消息类型:" + messageType);
        System.out.println("服务器端接收到消息数据长度:" + length);
        System.out.println("服务器端接收到消息数据:" + new String(content, CharsetUtil.UTF_8));
        System.out.println("服务器端接收到消息数量:"+(++count));

        //服务器会送数据给客户端,回送一个随机id值
        byte[] responseContent = UUID.randomUUID().toString().getBytes(CharsetUtil.UTF_8);
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setType(1);
        messageProtocol.setLength(responseContent.length);
        messageProtocol.setContent(responseContent);
        ctx.channel().writeAndFlush(messageProtocol);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

3.7、客户端实现

public class TcpClient {

    private String host;

    private int port;

    public TcpClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void run(){
        EventLoopGroup eventGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new TcpClientInitializer());
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new TcpClient("127.0.0.1",7000).run();
    }
}

3.8、客户端Initializer

public class TcpClientInitializer extends ChannelInitializer {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //获取到pipeline
        ChannelPipeline pipeline = socketChannel.pipeline();

        //编码器
        pipeline.addLast("MessageProtocolEncoder",new MessageProtocolEncoder());

        //解码器
        pipeline.addLast("MessageProtocolDecoder",new MessageProtocolDecoder());

        //加入业务处理的handler
        pipeline.addLast("handler",new TcpClientHandler());
    }
}

3.9、客户端Handler

public class TcpClientHandler extends SimpleChannelInboundHandler {

    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        //接收到数据并处理
        int messageType = msg.getType();
        int length = msg.getLength();
        byte[] content = msg.getContent();
        System.out.println("客户端接收到消息类型:" + messageType);
        System.out.println("客户端接收到消息数据长度:" + length);
        System.out.println("客户器端接收到消息数据:" + new String(content, CharsetUtil.UTF_8));
        System.out.println("客户器端接收到消息数量:"+(++count));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //发送10条你好,中国
        for (int i = 0; i < 10; i++) {
            String msg = "你好,中国 "+i;
            byte[] content = msg.getBytes(CharsetUtil.UTF_8);

            //创建协议包对象
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setType(1);
            messageProtocol.setLength(content.length);
            messageProtocol.setContent(content);
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

你可能感兴趣的:(Netty——ReplayingDecoder+自定义协议解决TCP粘包、拆包)