I've got an aedes MQTT broker and my MQTT client, but I can't seem to connect them.
In my app.js
I do the following:
(async function () {
try {
await startBroker();
await mqttClient();
} catch (e) {
console.error("ERROR: ", e);
process.exit();
}
})();
My startBroker function start aedes and streams it like so:
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()
});
})
};
and then my mqttClient
tries to connect, however I can never get to actually connect. I've tested it against the test mosquitto server which works fine
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);
});
}
Does anyone know why my broker doesn't seem to be working?
Could you clarify, how the broker is not working and what actually works? Where and how do you run the code?
When I put the code into a single file (changing
exports.
intoconst
), it does work. I had to add a semicolon after the function declaration ofmqttClient
, but after that, I get the following console output:This is the full code that can be copied right away. It runs in Node.js v12.15.0 on my macOS 10.15 Catalina.