简体   繁体   English

如何使用 MQTT 发送唯一消息?

[英]how to send a unique message with MQTT?

i need your help.我需要你的帮助。 I am creating a program with MQTT, it must execute commands written on a file and send the result to a topic.我正在使用 MQTT 创建一个程序,它必须执行写入文件的命令并将结果发送到主题。 I have already managed to execute the command and print the result on the terminal, but when I have to send it via MQTT it creates two messages, is it possible to send a message only with the result?我已经设法执行命令并在终端上打印结果,但是当我必须通过 MQTT 发送它时,它会创建两条消息,是否可以只发送带有结果的消息? how can I do?我能怎么做? thanks I'll put the code for reading the result of the command executed and the two messages it sends me.谢谢,我将把代码用于读取执行命令的结果以及它发送给我的两条消息。

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);
}

信息

The code you have is a line at a time, if the command outputs multiple lines then you are going to send multiple messages.您拥有的代码一次是一行,如果命令输出多行,那么您将发送多条消息。

You need to loop over the output from reader.readLine() store all the results and then publish the message.您需要从reader.readLine()遍历 output 存储所有结果,然后发布消息。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM