From 6e33e3f0ee952d768026fda82dc0000204e21c72 Mon Sep 17 00:00:00 2001
From: liusuyi <1951119284@qq.com>
Date: Tue, 18 Feb 2025 09:46:05 +0800
Subject: [PATCH] 222
---
ard-work/src/main/java/com/ard/tianyu/netty/handler/MessageProtocolEncoder.java | 28 ++++++++++++++++++++++------
1 files changed, 22 insertions(+), 6 deletions(-)
diff --git a/ard-work/src/main/java/com/ard/tianyu/netty/handler/MessageProtocolEncoder.java b/ard-work/src/main/java/com/ard/tianyu/netty/handler/MessageProtocolEncoder.java
index 8ed5690..3ff7b6c 100644
--- a/ard-work/src/main/java/com/ard/tianyu/netty/handler/MessageProtocolEncoder.java
+++ b/ard-work/src/main/java/com/ard/tianyu/netty/handler/MessageProtocolEncoder.java
@@ -1,16 +1,32 @@
package com.ard.tianyu.netty.handler;// MessageProtocolEncoder.java
-import com.ard.tianyu.netty.command.BaseCommand;
+import com.ard.common.utils.ByteUtils;
+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;
-public class MessageProtocolEncoder extends MessageToByteEncoder<BaseCommand> {
+@Slf4j
+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()); // 写入数据长度
- 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)
+ {
+ // 打印编码后的字节数组
+ 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);
}
}
--
Gitblit v1.9.3