【问题标题】:Can't connect to aedes MQTT broker无法连接到伊蚊 MQTT 代理
【发布时间】:2020-03-05 15:37:08
【问题描述】:

我有一个aedes MQTT 代理和我的 MQTT 客户端,但我似乎无法连接它们。

在我的app.js 中,我执行以下操作:

(async function () {
  try {
    await startBroker();
    await mqttClient();
  } catch (e) {
    console.error("ERROR: ", e);
    process.exit();
  }
})();

我的 startBroker 函数启动 aedes 并像这样流式传输它:

const aedes = require('aedes')();
const server = require('net').createServer(aedes.handle);
const port = 1883;

exports.startBroker = function() {
    return new Promise((res, rej) => {
        server.listen(port, function () {
            console.log(`MQTT Broker started on port ${port}`);
            return res()
        });
    })
};

然后我的mqttClient 尝试连接,但我永远无法真正连接。我已经针对运行良好的测试 mosquitto 服务器对其进行了测试

const mqtt = require('mqtt');

const client = mqtt.connect("mqtt://localhost:1883");

exports.mqttClient = function() {
    console.log("Connecting to MQTT Client");
    client.on("connect", ack => {
        console.log("MQTT Client Connected!");

        client.on("message", (topic, message) => {
            console.log(`MQTT Client Message.  Topic: ${topic}.  Message: ${message.toString()}`);
        });
    });

    client.on("error", err => {
        console.log(err);
    });
}

有人知道为什么我的经纪人似乎没有工作吗?

【问题讨论】:

    标签: node.js mqtt aedes


    【解决方案1】:

    您能否澄清一下,如何代理不工作以及实际工作在哪里以及如何运行代码?

    当我将代码放入单个文件(将exports. 更改为const)时,它确实有效。我不得不在mqttClient的函数声明后添加一个分号,但之后,我得到以下控制台输出:

    MQTT 代理在端口 1883 上启动
    连接到 MQTT 客户端
    MQTT 客户端已连接!

    这是可以立即复制的完整代码。它在我的 ma​​cOS 10.15 Catalina 上的 Node.js v12.15.0 中运行。

    const aedes = require('aedes')();
    const server = require('net').createServer(aedes.handle);
    const port = 1883;
    
    // exports.startBroker = function() {
    const startBroker = function() {
        return new Promise((res, rej) => {
            server.listen(port, function () {
                console.log(`MQTT Broker started on port ${port}`);
                return res()
            });
        })
    };
    
    const mqtt = require('mqtt');
    
    const client = mqtt.connect("mqtt://localhost:1883");
    
    //exports.mqttClient = function() {
    const mqttClient = function() {
        console.log("Connecting to MQTT Client");
        client.on("connect", ack => {
            console.log("MQTT Client Connected!");
    
            client.on("message", (topic, message) => {
                console.log(`MQTT Client Message.  Topic: ${topic}.  Message: ${message.toString()}`);
            });
        });
    
        client.on("error", err => {
            console.log(err);
        });
    }; // <-- semicolon added here
    
    (async function () {
      try {
        await startBroker();
        await mqttClient();
      } catch (e) {
        console.error("ERROR: ", e);
        process.exit();
      }
    })();
    

    【讨论】:

      最近更新 更多