mirror of
https://codeup.aliyun.com/67c68d4e484ca2f0a13ac3c1/ydc/jsowell-charger-web.git
synced 2026-04-21 03:25:12 +08:00
41 lines
1.6 KiB
Java
41 lines
1.6 KiB
Java
package com.jsowell.netty.decoder;
|
|
|
|
import io.netty.buffer.ByteBuf;
|
|
import io.netty.channel.ChannelHandlerContext;
|
|
import io.netty.handler.codec.ByteToMessageDecoder;
|
|
import io.netty.handler.codec.CorruptedFrameException;
|
|
|
|
import java.util.List;
|
|
|
|
public class CustomDecoder extends ByteToMessageDecoder {
|
|
private static final byte START_FLAG = (byte) 0x68;
|
|
|
|
@Override
|
|
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
|
|
// 检查可读数据长度是否大于等于起始标志符和数据长度字段的长度
|
|
if (in.readableBytes() >= 3) {
|
|
// 标记当前读取位置
|
|
in.markReaderIndex();
|
|
// 读取起始标志符
|
|
byte startFlag = in.readByte();
|
|
// 检查起始标志符是否正确
|
|
if (startFlag != START_FLAG) {
|
|
// 如果不正确,重置读取位置,并抛出异常
|
|
in.resetReaderIndex();
|
|
throw new CorruptedFrameException("Invalid start flag: " + startFlag);
|
|
}
|
|
// 读取数据长度
|
|
byte length = in.readByte();
|
|
// 检查可读数据长度是否大于等于数据长度字段的值
|
|
if (in.readableBytes() >= length) {
|
|
// 读取完整数据包
|
|
ByteBuf frame = in.readBytes(length + 2); // 包括校验位
|
|
out.add(frame);
|
|
} else {
|
|
// 如果可读数据长度不够,重置读取位置,并等待下一次读取
|
|
in.resetReaderIndex();
|
|
}
|
|
}
|
|
}
|
|
}
|