package com.ard.tianyu.netty.handler;// MessageProtocolDecoder.java import com.ard.tianyu.netty.command.BaseCommand; import com.ard.tianyu.netty.command.HeartbeatReplyCommand; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import lombok.extern.slf4j.Slf4j; import java.util.List; @Slf4j public class MessageProtocolDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { // 检查可读字节数是否足够 if (in.readableBytes() < 4) { return; // 不足以读取头部 } in.markReaderIndex(); // 标记当前读取位置 short dataHead = in.readShort(); if(dataHead != 0x6A77){ return; } short dataLength = in.readShort(); if (in.readableBytes() < dataLength) { in.resetReaderIndex(); // 如果不足,重置读取位置 return; } byte cmdCode = in.readByte(); BaseCommand command = null; // 根据 cmdCode 创建相应消息对象 if (cmdCode == 0x01) { // 注册回复消息 byte success = in.readByte(); // 读取是否成功 log.warn("注册回复: {}", success == 0x01 ? "成功" : "失败"); } if (cmdCode == 0x02) { // 注册回复消息 long timestamp = in.readLong(); // 读取时间戳 command = new HeartbeatReplyCommand(timestamp); // 创建心跳回复对象 log.debug("心跳回复: 时间戳 {}", timestamp); } if (command != null) { out.add(command); // 添加解码的命令对象到输出列表 } else { log.warn("无法识别的命令码: {}", cmdCode);//String.format("0x%02X", cmdCode & 0xFF) } } }