Server On Aedes JS does not work properly

55 Views Asked by At

I am currently setting up an MQTT server using Aedes, and the server is configured to use authentication. However, I am encountering several issues:

  1. When a client connects, 'server.on' does not display its console log.

  2. When a client disconnects, 'server.on' does not show its console log.

  3. However, when a client attempts to connect to the server, the client responds normally.

Solutions I have tried:

  1. Consolidating all configurations into one file.

  2. Adjusting the port as directed in (https://github.com/moscajs/aedes/issues/330).

What else should I do?

mqtt/broker.js

const self = this;
const { server, config } = require("../mqtt/mqtt.js"); // Mengimpor server dan config dari mqtt/mqtt.js

// console.log(server.config.credentials.user)

server.on('clientConnected', function (client) {
    console.log("Gateway connected", client.id);
    // console.log(`[CLIENT_CONNECTED] Client ${(client ? client.id : client)} connected to broker ${server.id}`);
});

server.on('clientDisconnect', function (client) {
    console.log("Gateway disconnected", client.id);
    // console.log(`[CLIENT_DISCONNECTED] Client ${(client ? client.id : client)} disconnected from broker ${server.id}`);
});

server.listen(config.server.mqtt_port, function () {
    server.authenticate = authenticate;
    console.log(`MQTT Broker started on port ${config.server.mqtt_port}`);

});

server.authenticate = (client, username, password, callback) ==> {
    password = Buffer.from(password, 'base64').toString();
    if (username === config.credentials.user && password === config.credentials.password) {
        return callback(null, true);
    }
    const error = new Error('Authentication Failed!! Please enter valid credentials.');
    console.log('Authentication failed.')
    return callback(error, false);
};

mqtt/mqtt.js

const aedes = require('aedes')()
var server = require('net').createServer(aedes.handle)
const config = require('../mqtt-config.js');
var settings = {port: config.server.mqtt_port};

module.exports = { server,config };

mqtt-config.js

const mqtt_config = {
    "server": {
        "dbhost": "localhost",
        "mqtt_port": 2002,
        "dbuser": "cdef",
        "dbpassword": "",
        "dbname": "abcdef"
    },
    "credentials":{
        "user": "cde",
        "password": "abc"
    }
};

module.exports = mqtt_config;

Can fix my ploblem at all

0

There are 0 best solutions below