update 电单车协议

This commit is contained in:
Guoqs
2024-08-26 14:45:19 +08:00
parent f27773ba05
commit c091b6dea7
10 changed files with 144 additions and 83 deletions

View File

@@ -1,40 +0,0 @@
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();
}
}
}
}