打印獲取出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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章