Home > Enterprise >  React application not connecting with local mqtt broker
React application not connecting with local mqtt broker

Time:04-04

I have setup a local mqtt broker using mosca as below

var mosca = require('mosca');
var settings = {
    port:1883
}

var server = new mosca.Server(settings);

server.on('ready', function(){
    console.log("ready");
});

Where I can publish and subscribe using the below respective codes

var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.43.xxx');
client.on('connect', function () {
    setInterval(function () {
        client.publish('myTopic', 'Hello mqtt');
        console.log('Message Sent');
    }, 5000);
});
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.43.xxx')
client.on('connect', function () {
    client.subscribe('myTopic')
})
client.on('message', function (topic, message) {
    console.log(message.toString())
})

but When I try to connect form my react application it never establish connection. Where I was using mqtt://test.mosquitto.org:8081 and it did work but when I changed the url to mqtt://192.168.43.xxx:1883 it don't connect anymore. What could be the problem?

EDIT : Any guide on setting up mqtt with web socket on node.js would be appreciated

CodePudding user response:

You can not use native MQTT from within the browser. To use MQTT, you need to use it over WebSockets.

so you should change the URL from mqtt://192.168.43.xxx:1883 to ws://192.168.43.xxx:[some other port number]

CodePudding user response:

So instead of mosca I am now using aedes and the below code worked. So to use ws:// in browser we have to listen for ws port in backend/broker.

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

const ws = require('websocket-stream')


const port = 1883;

server.listen(port, function () {
    console.log(`MQTT Broker running on port: ${port}`);
});

const wssPort = 1234
const host = '0.0.0.0' // localhost

var wsSslServer = require('http').createServer({})
ws.createServer({ server: wsSslServer}, aedes.handle)
wsSslServer.listen(wssPort, host, function () {
    console.log('WSS server listening on port', wssPort)
})

  • Related