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;
}
}