liusuyi
2024-10-22 de44eb3187c8a88c2942f8904701b96be09c61da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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<Object> 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.info("注册回复: {}", success == 0x01 ? "成功" : "失败");
        }
        if (cmdCode == 0x02) { // 注册回复消息
            long timestamp = in.readLong(); // 读取时间戳
            command = new HeartbeatReplyCommand(timestamp); // 创建心跳回复对象
            log.info("心跳回复: 时间戳 {}", timestamp);
        }
        if (command != null) {
            out.add(command); // 添加解码的命令对象到输出列表
        } else {
          //  log.warn("无法识别的命令码: {}", cmdCode);
        }
    }
}