1

I want to make mqtt request to interact with my own broker . It should be done (client) using react or next.js and mqtt.js package.

I was attempt, but when I inspect a browser , It seems my browser attempt to ws connection and it currupt: enter image description here

I was install this package :

npm i mqtt --save

Below are all stuffs which I attempt using these:

import React, { useEffect, useState } from "react";
import mqtt from "mqtt";

function Send() {
  const [status, setStatus] = useState("Not Connect");

  useEffect(() => {
    //const client = mqtt.connect("wss://test.mosquitto.org:8081/mqtt");
    const client = mqtt.connect("mqtt://171.22.25.40:1883");

    client.on("connect", () => {
      setStatus("Connect");

      client.subscribe("IHS", (err) => {
        if (!err) {
          client.publish("IHS", "Test Message");
        }
      });
    });
  }, []);

  return (
    <div>
      <p>{`Status: ${status}`}</p>
    </div>
  );
}

export default Send;

Is I missed an specific configuration for mqtt function ? How can I fix it?

Edit:

I append a configuration to mqtt variable like these snipped:

const options = {
      port: 1883,
      host: "171.22.25.40",
      protocol: "mqtt",
      keepalive: 10,
      protocolId: "MQTT",
      reconnectPeriod: 2000,
    };
    const client = mqtt.connect("mqtt://171.22.25.40:1883", options);

But nothing happened.

Edited: I use this config in the mosquito config file, from C# can connect to mqtt but can't connect to wss

port 1883
listener 9001
protocol websockets
allow_anonymous true
hardillb
  • 54,545
  • 11
  • 67
  • 105

1 Answers1

1

You can not use native MQTT protocol from within the browser, because the browsers JavaScript sandbox will not allow you to make arbitrary TCP connections. You can only make HTTP or WS connections.

The MQTT.js package will always convert any mqtt:// URL to a ws:// when run in the browser.

You will need to make sure your broker is configured to accept MQTT over WebScoket connections and set the port number in the URL to match.

hardillb
  • 54,545
  • 11
  • 67
  • 105
  • I edited the question and add the mosquito config file(please check out edited section ), I can't connect even with socket –  Nov 03 '22 at 11:28
  • Have you also changed the `options` object and the URL you are using to try and connect? Also if your web app is loaded over HTTPS then you will also need to configure the WebSockets listener with certificates to support `wss://` (or have something like nginx proxy for it) – hardillb Nov 03 '22 at 12:11