Home > Software engineering >  cannot connect to "mqtt://test.mosquitto.org" from React client
cannot connect to "mqtt://test.mosquitto.org" from React client

Time:12-10

I want to connect a client React app to the mosquitto test server. The "meat" React code involved:

import mqtt from 'mqtt';


    const mqttConnect = ("mqtt://192.168.1.157",{clientId:"mqttjs01"}) => {
        setConnectStatus('Connecting');
        console.log(mqttOptions)
        setClient(mqtt.connect(host, mqttOptions));
    };

The error on the web page is:

ws.js:108 WebSocket connection to 'ws://test.mosquitto.org/' failed: 

so one challenge I see is the insistence of a web socket. (ws protocol). Then another challenge is my ultimate goal is to talk to a mosquitto broker running on a Raspberry Pi (port 1883, which I thought the mqqt:// was addressing). The Raspberry Pi is not using websockets.

It appears clear to me that I am clueless. Any guidance / pointing in the right direction...greatly appreciated. Thank you.

CodePudding user response:

With React you have to use WebSockets (because it effectively runs in the broswers) so your URL should start with ws:// not mqtt://.

Secondly you need to specify a port because there is no default port for MQTT over Websockets (and the WebSockets library will default to port 80)

So having checked the table of port numbers on test.mosquitto.org you should be using:

ws://test.mosquitto.org:8080/

p.s your client id's also probably need to have a lot more entropy (be random) otherwise you'll only ever have 1 connected client.

As for your local setup, you will need to configure mosquitto to listen on 2 different ports:

  • One for normal MQTT (default 1883)
  • One for MQTT over WebSockets (any port you want)

e.g. a conf file something like:

allow_anonymous true

listener 1883

listener 9001
protocol websockets

Mosquitto will share the same topic space between both listeners.

  • Related