打印获取出netty获取电表上传的16进制的原始报文。

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();
}
发布了22 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41969813/article/details/88788226