netty解析类中获取原始报文字符串,将ByteBuf buffer转为16进制String字符串
protected Object decode(ChannelHandlerContext context, ByteBuf buffer) throws Exception { if (buffer == null) { return null; } // logger.info("原始报文---------------:" + convertByteBufToString(buffer)); System.out.println("原始报文----------------:" + convertByteBufToString(buffer));
}
public static String convertByteBufToString(ByteBuf buf) throws UnsupportedEncodingException {
String str;
byte[] bytes;
if (buf.hasArray()) { // 处理堆缓冲区
str =
new String(
buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes(), "UTF-8");
bytes = new byte[] {};
toHexString(bytes);
System.out.println("堆缓冲区-------:");
System.out.println(str);
} else { // 处理直接缓冲区以及复合缓冲区
bytes = new byte[buf.readableBytes()];
buf.getBytes(buf.readerIndex(), bytes);
// str = new String(bytes, 0, buf.readableBytes(), "UTF-8");
toHexString(bytes);
}
String regex = "(.{2})";
return toHexString(bytes).replaceAll(regex, "$1 ").toUpperCase();
}
/**
* 字节数组转成16进制表示格式的字符串
*
* @param byteArray 需要转换的字节数组
* @return 16进制表示格式的字符串
*/
public static String toHexString(byte[] byteArray) {
if (byteArray == null || byteArray.length < 1)
throw new IllegalArgumentException("this byteArray must not be null or empty");
final StringBuilder hexString = new StringBuilder();
for (int i = 0; i < byteArray.length; i++) {
if ((byteArray[i] & 0xff) < 0x10) // 0~F前面不零
hexString.append("0");
hexString.append(Integer.toHexString(0xFF & byteArray[i]));
}
return hexString.toString().toLowerCase();
}