package com.ard.work.component.netty.handler;// MessageProtocolEncoder.java import com.ard.common.utils.ByteUtils; import com.ard.work.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; import java.util.Arrays; @Slf4j public class MessageProtocolEncoder extends MessageToByteEncoder { @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("encodedBytes message bytes: {}------", encodedBytes); log.warn("Encoded message bytes: {}------", Arrays.toString(encodedBytes)); // 将字节数组转换为十六进制格式 String hexString = ByteUtils.bytesToHexWithSpaces(encodedBytes); log.warn("Encoded message in hex: {}", hexString); } public byte[] testParameters() { String data = "74 79 01 3C 44 42 4D 32 35 30 39 37 34 30 36 35 30 30 38 D1 00 10 08 01 15 00 00 70 41 1D 00 00 00 41 22 4A 09 06 9C E7 80 8B F0 59 40 11 08 98 33 BA 07 1D 3F 40 1D 00 00 F0 41 25 00 00 00 41 2A 09 08 01 15 00 00 20 41 18 02 2A 09 08 03 15 00 00 80 3F 18 02 2A 09 08 04 15 00 00 80 3F 18 02 30 01 58 FF FF FF FF FF FF FF FF FF 01 22 55 09 F1 BC 12 50 7A F0 59 40 11 08 98 33 BA 07 1D 3F 40 1D 00 00 20 42 25 00 00 00 41 2A 09 08 09 15 00 00 A0 41 18 02 2A 09 08 06 15 00 00 20 42 18 02 2A 09 08 07 15 00 00 20 42 18 02 2A 09 08 08 15 00 00 20 42 18 02 30 01 58 FF FF FF FF FF FF FF FF FF 01 22 3F 09 F1 BC 12 50 7A F0 59 40 11 91 92 E4 DA CC 1C 3F 40 1D 00 00 48 42 25 00 00 00 41 2A 09 08 09 15 00 00 70 41 18 02 2A 09 08 0A 15 00 00 40 40 18 02 30 01 58 FF FF FF FF FF FF FF FF FF 01 22 34 09 06 9C E7 80 8B F0 59 40 11 91 92 E4 DA CC 1C 3F 40 1D 00 00 70 42 25 00 00 00 41 2A 09 08 02 15 00 00 80 3F 18 02 30 01 58 FF FF FF FF FF FF FF FF FF 01 30 32 70 32"; String[] hexStrings = data.split(" "); StringBuilder sb = new StringBuilder(); sb.append("byte[] encodedBytes = {"); for (int i = 0; i < hexStrings.length; i++) { sb.append("(byte) 0x").append(hexStrings[i]); if (i < hexStrings.length - 1) { sb.append(", "); } } sb.append("};"); return sb.toString().getBytes(); } }