Netty14——TCP的粘包和拆包

一、TCP的粘包和拆包

 TCP 是面向连接的,也是面向流的。为了提供高可靠性的服务,收发两端(客户端和服务器端)要有一一成对的socket。发送端为了将多个发给接收端的包更有效的发给对方,使用了优化方法(Nagle算法),将多次间隔较小且数据量小的数据,合并成一个大的数据块,然后进行封包。这样做虽然提高了效率,但是接收端就难于分辨出完整的数据包了,因为面向流的通信是无消息保护边界的。
 由于TCP无消息保护边界, 需要在接收端处理消息边界问题,也就是我们所说的粘包、拆包问题。如下图:
在这里插入图片描述
 假设客户端分别发送了两个数据包D1和D2给服务端,由于服务端一次读取到的字节数是不确定的,故可能存在以下四种情况:
  1) 服务端分两次读取到了两个独立的数据包, 分别是D1和D2,没有粘包和拆包
  2) 服务端一次接收到了两个数据包,D1和D2 粘合在一起,称之为TCP粘包
  3) 服务端分两次读取到了数据包,第一次读取到了完整的D1包和D2包的部分内容,第 二次读取到了D2包的剩余内容,这称之为 TCP 拆包
  4) 服务端分两次读取到了数据包,第一次读取到了D1包的部分内容D1_1,第二次读取到了D1包的剩余部分内容D1_2和完整的D2 包

二、粘包和拆包示例

 服务端:

public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

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

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);

        String messages = new String(buffer, Charset.forName("utf-8"));
        System.out.println("服务器端接收到消息:" + messages);
        System.out.println("服务器端接收到消息数量:" + (++this.count));

        ByteBuf responseByteBuf = Unpooled.copiedBuffer(UUID.randomUUID().toString() + " ", Charset.forName("utf-8"));
        ctx.writeAndFlush(responseByteBuf);
    }
}

 客户端:

public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 使用客户端发送10条数据
        for (int i = 0; i < 10; ++i) {
            ByteBuf buffer = Unpooled.copiedBuffer("Hello,server " + i, Charset.forName("utf-8"));
            ctx.writeAndFlush(buffer);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        String messages = new String(buffer, Charset.forName("utf-8"));
        System.out.println("客户端接收到消息:" + messages);
        System.out.println("客户端接收到消息数量:" + (++this.count));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
三、粘包和拆包的解决方案

 关键就是要解决服务器端每次读取数据长度的问题,这个问题解决了,就不会出现服务器多读或少读数据的问题,从而就避免了TCP 的粘包、拆包 。可以采用自定义协议 + 编解码器的方式来解决这个问题。
 示例:要求客户端发送 5 个 Message 对象,客户端每次发送一个 Message 对象;服务器端每次接收一个Message对象,分5次进行解码, 每读取到一个Message , 会回复一个 Message 对象给客户端
 自定义协议包:

public class MessageProtocol {

	// 标识发送内容的长度:很重要
    private int len;

    private byte[] content;

    public int getLen() {
        return len;
    }

    public void setLen(int len) {
        this.len = len;
    }

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

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

 自定义编码器:

public class MyMessageEncoder extends MessageToByteEncoder<MessageProtocol> {

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

 自定义解码器:

public class MyMessageDecoder extends ReplayingDecoder<Void> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("MyMessageDecoder.decode 被调用");
        // 将得到的二进制字节码转为MessageProtocol对象
        int length = in.readInt();
        byte[] content = new byte[length];
        in.readBytes(content);
        // 封装成MessageProtocol对象,传递给下一个handler
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(length);
        messageProtocol.setContent(content);
        out.add(messageProtocol);
    }
}

 客户端发送消息:发送的消息需封装为自定义协议包

public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 客户端发送5条数据
        for (int i = 0; i < 5; i++) {
            String mes = "今天天气冷,吃火锅";
            byte[] content = mes.getBytes(Charset.forName("utf-8"));
            int length = mes.getBytes(Charset.forName("utf-8")).length;
            // 创建自定义协议包对象
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(length);
            messageProtocol.setContent(content);
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
    	// 处理收到的消息
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端接收到的消息如下:");
        System.out.println("长度:" + len);
        System.out.println("内容:" + new String(content, Charset.forName("utf-8")));
        System.out.println("客户端接收到的消息数量=" + (++this.count));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常消息:" + cause.getMessage());
        ctx.close();
    }
}

 服务端接收和回复消息:

public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

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

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        // 接收到数据并处理
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("服务器接收到消息如下:");
        System.out.println("长度:" + len);
        System.out.println("内容:" + new String(content, Charset.forName("utf-8")));
        System.out.println("服务端接收到的消息包数量=" + (++this.count));

        // 回复消息
        String responseContent = UUID.randomUUID().toString();
        int responseLen = responseContent.getBytes("utf-8").length;
        byte[] contentBytes = responseContent.getBytes("utf-8");
        // 构建自定义协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(responseLen);
        messageProtocol.setContent(contentBytes);
        ctx.writeAndFlush(messageProtocol);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值