0

我有一个伊蚊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尝试连接,但是我永远无法真正连接。我已经针对工作正常的测试蚊子服务器对其进行了测试

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

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

4

1 回答 1

0

您能否澄清一下,经纪人是如何不工作的以及实际上是什么工作你在哪里以及如何运行代码?

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

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

这是可以立即复制的完整代码。它在我的macOS 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();
  }
})();
于 2020-03-31T21:42:31.637 回答