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