【问题标题】:how to send a unique message with MQTT?如何使用 MQTT 发送唯一消息?
【发布时间】:2022-01-02 11:24:11
【问题描述】:

我需要你的帮助。我正在使用 MQTT 创建一个程序,它必须执行写入文件的命令并将结果发送到主题。我已经设法执行命令并在终端上打印结果,但是当我必须通过 MQTT 发送它时,它会创建两条消息,是否可以只发送带有结果的消息?我能怎么做?谢谢,我会把代码用于读取执行命令的结果和它发送给我的两条消息。

String result;
while ((result=reader.readLine()) != null) {
  System.out.println(result);
  final  MqttTopic timeTopic = client.getTopic(TOPIC);
  timeTopic.publish(new MqttMessage(result.getBytes()));
  System.out.println(" - Published data. Topic: " + timeTopic.getName() + "  Message: " + result);
}

【问题讨论】:

    标签: java mqtt


    【解决方案1】:

    您的代码是一次一行,如果命令输出多行,那么您将发送多条消息。

    您需要遍历reader.readLine() 的输出存储所有结果,然后发布消息。

    String line;
    String output = "";
    while ((line=reader.readLine()) != null) {
      System.out.println(line);
      output += line + "\n";
    }
    final MqttTopic timeTopic = client.getTopic(TOPIC);
    timeTopic.publish(new MqttMessage(line.getBytes()));
    System.out.println(" - Published data. Topic: " + timeTopic.getName() + "  Message: " + result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      • 1970-01-01
      相关资源
      最近更新 更多