0

I am developing a NextJS web app for my project and I have this code:

import { connect, AsyncMqttClient } from "async-mqtt";

const Page = () => {

let [client, setClient] = useState<AsyncMqttClient | null>(null);

useEffect(() => {
    if (client) {
        console.log(client);
        client.on("connect", () => {
            console.log("Reconnecting!");
        });
        client.on("error", (err) => {
            console.error("Connection error: ", err);
            client?.end();
        });
        client.on("reconnect", () => {
            console.log("Reconnecting!");
        });
        client.on("message", (topic, message) => {
            const payload = { topic, message: message.toString() };
            console.log(payload);
        });
    } else {
        setClient(connect("wss://<my hivemqt broker>", {
            username: "username",
            password: "password",
            clientId: "oeirfkgtjn",
            port: 8884,
            protocol: "wss",
            keepalive: 60,
            clean: true
        }));
    }
}, [client]);
    return (
        <>...</>
    );
};

I'm running a HiveMQ broker and I want to be able to subscribe to it and stuff but the thing is I'm only met with errors in the console:

ws.js?725c:109 WebSocket connection to 'ws://<my broker URL>:8884/' failed: 

createBrowserWebSocket @ ws.js?725c:109
browserStreamBuilder @ ws.js?725c:136
wrapper @ index.js?59e6:155
MqttClient._setupStream @ client.js?86b2:415
MqttClient._reconnect @ client.js?86b2:1105
eval @ client.js?86b2:1125

I connected to my broker using the online WebSocket demo and everything worked fine with providing the exact same information as the MQTT.js client. Does anybody have an idea of what the issue could be?

Things I tried so far

  • I tried different ports such as 8883, 1883, and 1884
  • I also tried changing the protocol from wss to ws
Pro Poop
  • 357
  • 5
  • 14
  • Open your browsers devtools (generally F12), attempt to connect, and then check the network and console tabs for info (this will probably point you towards the cause). Edit your question with details of what you find (currently there are too many unknowns to guess at a cause). Please also confirm what port you used in the online demo and whether you checked the "SSL" checkbox (info about your broker and relevant sections from it's logs might also help). – Brits Jul 07 '22 at 05:06
  • Also you need to read the broker configuration and see exactly which port (if any) have been configured to use MQTT over WebSockets. – hardillb Jul 07 '22 at 07:10

0 Answers0