小言_互联网的博客

代码 - Java - Netty - TCP粘包拆包(自定义协议)

325人阅读  评论(0)

粘包/拆包解决办法

消息定长:报文大小固定长度,不够空格补全(不采用-无用字节)
固定结尾:每条报文结尾位置固定,报文中不能出现该结尾字符(不采用)
消息定长衍生版:根据消息可计算出消息总长度,开头 包长度 协议号 消息体 结尾 (采用)

粘包/拆包原理

每次接受到数据后会执行“SmartCarDecoder”自定义拆包方法,将数据进行拆分
拆分完毕后直接调用“out.add(protocol);”方法返回ServerHandler中channelRead方法
channelRead方法中Object msg即为protocol类型[可通过强转]

自定义协议-代码实现
(1)协议的封装

package com.ztjy.server.dao;

import lombok.Data;

/**
 * 描述 : 自定义协议
 * 作者 : Jayson
 * 日期 : 2019/9/19 11:08 上午
 */
@Data
public class SmartCarProtocol {
    /**
     * 消息的开头
     */
    private byte[] smartHead = {0x78, 0x78};
    /**
     * 包长度
     */
    private byte contentLength;
    /**
     * 协议类型
     */
    private byte smartType;
    /**
     * 消息的内容
     */
    private byte[] content;
    /**
     * 消息的结尾
     */
    private byte[] smartEnd = {0x0d, 0x0a};

    /**
     * 用于初始化,SmartCarProtocol
     */
    public SmartCarProtocol(byte smartType, byte[] content) {
        this.smartType = smartType;

转载:https://blog.csdn.net/qq_35571217/article/details/101014513
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场