Не удается подключиться к брокеру aedes MQTT - PullRequest
0 голосов
/ 05 марта 2020

У меня есть aedes MQTT-брокер и мой MQTT-клиент, но я не могу их соединить.

В моем app.js я делаю следующее:

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

Моя функция startBroker запускает и выполняет потоковую передачу следующим образом:

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

Кто-нибудь знает, почему мой брокер не работает?

1 Ответ

0 голосов
/ 01 апреля 2020

Не могли бы вы уточнить, как брокер не работает и что на самом деле работает ? Где и как вы запускаете код?

Когда я помещаю код в один файл (изменяя exports. в const), он работает , Мне пришлось добавить точку с запятой после объявления функции mqttClient, но после этого я получаю следующий вывод консоли:

MQTT Broker запущен на порту 1883 Подключение к клиенту MQTT Клиент MQTT подключен!

Это полный код, который можно скопировать сразу. Он работает в Node.js v12.15.0 на моем macOS 10.15 Catalina .

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();
  }
})();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...