使用 MQTT 和 Node.js 不断发布消息

Message getting published endlessly with MQTT and Node.js

我的一台机器上有一个 mosquitto 代理 运行(例如:mqtt://10.0.0.50:1883)。 我正在尝试在 IoT 网关中将 MQTT 与 Node 结合使用以从移动应用程序接收消息,并根据发送消息的主题执行某些功能。操作完成后,从移动应用网关发布另一条关于同一主题的消息。

网关端:

 client.on('connect', function () {
    if (client.connected) {      
        client.subscribe(topics, {qos: 1}, function (err, granted) {        
            console.log('Subscribed to topics: ' + JSON.stringify(granted));        
        });
    } 
 });

client.on('message', function (topic, message) {
    switch (topic.toUpperCase()) {
        case 'TEST':
            console.log('test topic Called');
            client.publish(topic, "test topic response msg", {qos: 1}, 
            function () {
                console.log("message response sent");
            });
    }
});

我用另一个示例 node.js 代码尝试了这段代码。

客户端:

client.on('connect', function () {
    if (client.connected) {      
        client.subscribe("test", {qos: 1}, function (err, granted) {            
            console.log('Subscribed to topics: ' + JSON.stringify(granted));            
        });
        client.publish("test", "send_me_test", {qos: 1}, function () {
            console.log("request message published");
        });
    } 
});

client.on('message', function (topic, message) {
    console.log("Topic: " + topic + " request: " + message);
});

我在 运行 client.js 之后得到的响应:

Connected to the broker at: mqtt://10.0.0.50:1883
Subscribed to topics: [{"topic":"test","qos":1}]
message published
Topic: test request: send_me_test
Topic: test request: test topics response msg
Topic: test request: test topics response msg
Topic: test request: test topics response msg

无休止地进行下去。

网关端:

Jun 21 08:53:56 intel-quark api-server[16975]: test topic Called
Jun 21 08:53:56 intel-quark api-server[16975]: publishing response for topic: test with data: "test topics response msg"
Jun 21 08:53:56 intel-quark api-server[16975]: message published

不断重复。

我不明白为什么会这样。我想要的输出是一个响应发布一个请求发布。

您的网关订阅的主题与其发布的主题相同,因为它将收到自己的消息,这些消息将永远循环。

响应与收到消息相同的主题通常不是一个好主意,除非消息正文中有一些东西可以将其标记为可以检查以防止出现此类循环的响应。