Netty增加自定义解码器解决粘包分包问题

netty框架自带的粘包分包解码器

FixedLengthFrameDecoder (固定长度解码器)
DelimiterBasedFrameDecoder(分隔符解码器)
LineBasedFrameDecoder("\r\n"换行符解码器)

以上这些可以解决一般情况下的问题

一些特殊规则下,我们需要自定义解码器

例如:aa 0a 00 00 00 02 b2 00 00 00 00 00 be
0xaa为固定数据帧头
0x0a为红色部分的数量
0xbe为数据校验和
这样的数据帧解析就需要用到自定义解析器,可以参考netty框架自带的解析器源码来进行我们需要的规则开发
自定义解析器需要继承ByteToMessageDecoder类

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class DlhFrameDecoder extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		Object decoded = decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }
	}

	private Object decode(ChannelHandlerContext ctx, ByteBuf in) {
		byte aa = (byte) 0xAA;
		int index = indexOf(in,aa);
		if(index != -1){
			if (in.readableBytes() < index) {
	            return null;
	        }
			return in.readSlice(index).retain();
		}
		return null;
	}
	
	//数据和
	public static byte  getDataAdd(byte[] bs){
		byte he = 0;
		if(bs != null){
			for (int i = 0; i < bs.length; i++) {
				he += bs[i];
			}
		}
		return he;
	}
	
	/**
     * Returns the number of bytes between the readerIndex of the haystack and
     * the first needle found in the haystack.  -1 is returned if no needle is
     * found in the haystack.
     */
    private static int indexOf(ByteBuf haystack, byte b) {
        for (int i = 0; i < haystack.writerIndex(); i ++) {
            if(haystack.getByte(i) == b){
            	int index = i+haystack.getByte(i+1)+3;
            	int he = haystack.getByte(index-1);
            	byte[] hh = new byte[index-i-2];
            	haystack.getBytes(i+1, hh, 0, hh.length);
            	if(he == getDataAdd(hh)){
            		return index;
            	}
            }
        }
        return -1;
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值