Mqtt使用nodejs发布数组的每个元素

Mqtt publish each element of an array using nodejs

我有一个 Mqtt 客户端。我需要它以 5 秒的间隔发布每个元素并在 on_message 回调中接收每个元素。但是我的代码发布每个元素的次数与数组长度相同。

例子-

我的代码

var mqtt    = require('mqtt');
var client  = mqtt.connect("mqtt://broker.emqx.io:1883",{clientId:"mqtt_AYA"});

var arr = [1,2,3,4];
var options={
    retain:true,
    qos:1};
    
client.on("connect",function(){ 
    console.log("connected  "+ client.connected);
    })

arr.forEach(no => {
    client.on('message',function(topic, message, packet){
        console.log("message is "+ JSON.parse(message));
        // console.log("topic is "+ topic);
    });
    
    setInterval(function(){client.publish('/topic', JSON.stringify(no), options)},5000);

    client.subscribe('/topic', {qos:1});

});

结果-

connected  true
message is 1
message is 1
message is 1
message is 1
message is 2
message is 2
message is 2
message is 2
message is 3
message is 3
message is 3
message is 3
message is 4
message is 4
message is 4
message is 4
[5 secs interval]
Repetition of above 

但我需要-

connected  true
message is 1
[5 secs interval]
message is 2
[5 secs interval]
message is 3
[5 secs interval]
message is 4
[5 secs interval]
and end the client

您设置的Interval 和subscribe 在forEach 循环中。这意味着您同时开始 4 个间隔。由于每个值都订阅了每条消息,因此您有 4 个订阅者。当所有 setIntervals 同时发布消息时,所有 4 个订阅者都会显示消息。因此得到你看到的结果。