MQTT сжатие данных - PullRequest
       29

MQTT сжатие данных

0 голосов
/ 16 апреля 2020

В данный момент я пытаюсь выяснить, поддерживает ли MQTT автоматическое c сжатие данных. Например, если я комбинирую MQTT с TLS, я могу использовать параметры сжатия TLS. Есть ли что-нибудь подобное для MQTT? Или издательское приложение должно сжимать свои данные самостоятельно и затем может отправлять сжатые данные с помощью MQTT?

До сих пор я прочитал и не смог найти никакой конкретной c информации о том, поддерживает ли MQTT Сжатие данных или нет.

Спасибо за помощь:)

Ответы [ 2 ]

1 голос
/ 16 апреля 2020

MQTT - это просто транспорт, он будет переносить любые байты, которые вы дадите ему в качестве полезной нагрузки (до 256 МБ), и не изменяет их каким-либо образом.

Если вы хотите сначала сжать полезную нагрузку, то полностью зависит от вас.

0 голосов
/ 17 апреля 2020

Я создал класс-оболочку JZIP для моего проекта UFM (Universal File Mover) с открытым исходным кодом Java. Вы можете скачать исходный код с здесь .

Вот только класс JZip. У него есть 2 метода: compressData и depressData. Оба ожидают байт [] для ввода и дают байт [] в качестве вывода. Это супер просто в использовании.

package com.capitalware.ufm.handlers;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import com.capitalware.ufm.UFM;

/**
 * This class will handle all of UFM's compression and decompression work.
 * @author Roger Lacroix
 * @version 1.0
 * @license Apache 2 License
 */
public class JZip
{
   /**
    * The constructor - make sure nothing instantiates this class.
    * It must be accessed in a static way.
    */
   private JZip()
   {}

   /**
    * This method will compress a byte array of data.
    *
    * @param inputData an array of bytes
    * @return byte array of the contents of the file.
    */
   public static byte[] compressData(byte[] inputData)
   {
      // Create the compressor with highest level of compression
      Deflater compressor = new Deflater();
      compressor.setLevel(Deflater.BEST_COMPRESSION);

      // Give the compressor the data to compress
      compressor.setInput(inputData);
      compressor.finish();

      // Create an expandable byte array to hold the compressed data.
      // You cannot use an array that's the same size as the orginal because
      // there is no guarantee that the compressed data will be smaller than
      // the uncompressed data.
      ByteArrayOutputStream bos = new ByteArrayOutputStream(inputData.length);

      // Compress the data
      byte[] buf = new byte[65536];
      while (!compressor.finished())
      {
         int count = compressor.deflate(buf);
         bos.write(buf, 0, count);
      }
      try
      {
         bos.close();
      }
      catch (IOException e)
      {
         UFM.logger.fatal("IOException: " + e.getLocalizedMessage());
      }

      // return compressed data
      return bos.toByteArray();
   }

   /**
    * This method will decompress a byte array of compressed data.
    *
    * @param compressedData an array of bytes
    * @return byte array of uncompressed data
    */
   public static byte[] decompressData(byte[] compressedData)
   {
      // Create the decompressor and give it the data to compress
      Inflater decompressor = new Inflater();
      decompressor.setInput(compressedData);

      // Create an expandable byte array to hold the decompressed data
      ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);

      // Decompress the data
      byte[] buf = new byte[65536];
      while (!decompressor.finished())
      {
         try
         {
            int count = decompressor.inflate(buf);
            bos.write(buf, 0, count);
         }
         catch (DataFormatException e)
         {
            UFM.logger.fatal("DataFormatException: " + e.getLocalizedMessage());
         }
      }
      try
      {
         bos.close();
      }
      catch (IOException e)
      {
         UFM.logger.fatal("IOException: " + e.getLocalizedMessage());
      }

      // return uncompressed data
      return bos.toByteArray();
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...