MQTT在页面刷新时接收多个消息

时间:2019-07-14 01:53:05

标签: node.js socket.io mqtt

我有一个运行在前端的Express网页上的node.js服务器。我正在使用socket.io在我的网页和index.js之间进行通信,以便该网页在收到消息后会自动更新。我一般对javascript和node都是陌生的,将尽我所能尽力解释这一点。

我试图尽可能地隔离问题。该网页目前没有显示任何内容,但是在连接到节点服务器后,它将发送主题以通过socket.io

进行订阅。

这是我的index.js代码

var express = require("express");
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var mqtt = require('mqtt');
var broker = 'mqtt:localhost'
var mqtt_client = mqtt.connect(broker);
var port = process.env.PORT || 3000;

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){

    // Client Connects prints this
    console.log('a user connected');

    // Client disconnects prints this
    socket.on('disconnect', function(){
      console.log('user disconnected');
      mqtt_client.unsubscribe("bedroom/lights");
    });

    // When Client emits to subscribe
    socket.on("subscribe", (data) => {
      console.log("Subscribe > topic: " + data.topic);
      // MQTT subscribe broker topic
      mqtt_client.subscribe(data.topic);
    });

    // When Client emits to publish 
    socket.on("publish", (data) => {
      console.log("Publish > topic: " + data.topic + ", message: " + data.message);
      // MQTT publish to broker 
      mqtt_client.publish(data.topic, data.message, { qos: 0, retain: false });
    });

    // When MQTT receives a message
    mqtt_client.on("message", (topic, message, packet) => {
      console.log('received message %s %s', topic, message)

    });

  });

http.listen(port, function () {
  console.log('listening on *:' + port);
});

加载网页时运行的我的app.js文件具有此代码

(document).ready(function () {
    var socket = io();
    socket.on("connect", () => {
        console.log("Connected to server!!!");
        socket.emit("subscribe", { topic: "#" });
        socket.emit("publish", { topic: "bedroom/client/connection", message: "Client Connected" });
    });
});

此代码最初运行良好,我得到以下输出:

> node index.js

listening on *:3000
a user connected
Subscribe > topic: #
Publish > topic: bedroom/client/connection, message: Client Connected
received message bedroom/client/connection Client Connected

但是如果刷新页面,我会得到:

user disconnected
a user connected
Subscribe > topic: #
Publish > topic: bedroom/client/connection, message: Client Connected
received message bedroom/client/connection Client Connected
received message bedroom/client/connection Client Connected

我似乎收到多封邮件,如果我再次刷新页面,将会收到第三封邮件。我正在运行另一个单独的程序,该程序订阅所有mqtt代理主题并打印其消息。有趣的是,节点程序仍将单个消息发送给代理,但是接收方面会根据我刷新页面的次数打印倍数。解决这个问题的任何帮助都将很棒。

0 个答案:

没有答案