liusuyi
2024-10-30 05ba868736725db54db1944ed5cf7a95d14efc37
ard-work/src/main/java/com/ard/tianyu/netty/handler/MessageProtocolEncoder.java
@@ -1,29 +1,23 @@
package com.ard.tianyu.netty.handler;// MessageProtocolEncoder.java
import com.ard.tianyu.netty.command.BaseCommand;
import com.ard.tianyu.netty.command.BaseCmd;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
@Slf4j
public class MessageProtocolEncoder extends MessageToByteEncoder<BaseCommand> {
public class MessageProtocolEncoder extends MessageToByteEncoder<BaseCmd> {
    @Override
    protected void encode(ChannelHandlerContext ctx, BaseCommand command, ByteBuf out) throws Exception {
        out.writeShort(command.getDataHeader()); // 写入帧头
        out.writeShort(command.getDataLength()); // 写入数据长度
        if(command.getBoxSn() != null) {
            out.writeBytes(command.getBoxSn());
        }// 写入指令编号
        out.writeByte(command.getCmdCode()); // 写入指令编号
    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)
    {
        // 打印编码后的字节数组