liusuyi
2025-03-22 fe63fd580c5b65fa398dfe1fdf44466b26c6aadd
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
package com.ard.tianyu.component.netty.handler;// MessageProtocolEncoder.java
 
import com.ard.common.utils.ByteUtils;
import com.ard.tianyu.component.netty.command.BaseCmd;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
 
@Slf4j
public class MessageProtocolEncoder extends MessageToByteEncoder<BaseCmd> {
    @Override
    protected void encode(ChannelHandlerContext ctx, BaseCmd command, ByteBuf out) throws Exception {
 
        command.encode(out); // 编码具体负载
        // 打印
        if(command.getCmdCode()!=0x02) {
            printHex(out);
        }
    }
    // 打印编码后的字节数组
    private void printHex(ByteBuf out)
    {
        // 打印编码后的字节数组
        byte[] encodedBytes = new byte[out.readableBytes()]; // 创建字节数组,大小为可读字节数
        out.getBytes(out.readerIndex(), encodedBytes); // 读取ByteBuf中的字节到字节数组中
        // log.warn("Encoded message bytes: {}", Arrays.toString(encodedBytes));
        // 将字节数组转换为十六进制格式
        String hexString = ByteUtils.bytesToHexWithSpaces(encodedBytes);
        log.warn("Encoded message in hex: {}", hexString);
    }
}