2

I have this mqtt connection that works fine when I run it in nodeJS ... but when I move it into a react component I get this error:

Error during WebSocket handshake: net::ERR_CONNECTION_RESET

I've read this is caused by something to do with default ports here ... Usage of MQTT protocol in React but I can't find an answer I understand enough to solve it.

Can anyone help? Cheers

import React, { Component } from "react";
import mqtt from "mqtt";

let topic = "vendingmachine2/command";
const options = {
  port: 16987,
  host: "mqtt://address.cloudmqtt.com",
  clientId: "***",
  username: "***",
  password: "***",
  keepalive: 60,
  reconnectPeriod: 1000,
  protocolId: "MQIsdp",
  protocolVersion: 3,
  clean: true,
  encoding: "utf8",
  timeout: 3,
  useSSL: true
};
function CheckoutForm() {
const MQTTConnect = () => {
    const client = mqtt.connect("mqtt://address.cloudmqtt.com", options);
    client.on("connect", function() {
      // When connected
      console.log("connected");
      client.subscribe("vendingmachine2/feedback", error => {
        if (error) console.error(error);
        else {
          client.publish(topic, "0");
        }
      });
      openDoor();
    });
    client.on("message", (topic, message) => {
      console.log(topic, message.toString());
    });
    function openDoor() {
      let door = [1, 2];
      for (let i = 0; i < door.length; i++) {
        client.publish(topic, `${door[i]}`);
      }
    }
};
return (
    <div>

        <button onClick={MQTTConnect}>asdasd</button>

    </div>
  );
}
export default CheckoutForm;

4 Answers 4

2

You are trying to force a native MQTT connection using the mqtt:// schema for the broker URL.

The problem is when the ReactJS code runs in the browser it can't use native MQTT (because of the browser sandbox), you need to use MQTT over Websockets.

You do this by changing the URL schema to wss:// (MQTT over Secure Websockets) and change the port number. The Cloudmqtt docs say the port will be 36987 rather than 16987.

You should be able to use MQTT over Websockets from NodeJS as well as ReactJS.

Sign up to request clarification or add additional context in comments.

Comments

2

the URL schema is to be changed to wss:// for it to work and the port has to be changed to the websocket's port instead of the instance's port

Comments

2

working solution

install precompiled-mqtt npm package

import mqtt from "precompiled-mqtt";

const URL = "ws://x.xxx.xx.xxx:8000";
  const [client, setClient] = React.useState(null);

  useEffect(() => {
    mqttConnect();
  }, []);


const mqttConnect = () => {
    const client = mqtt.connect(URL, {
      // clientId: "mqttjs_" + Math.random().toString(16).substr(2, 8),
      connectTimeout: 5000,
      hostname: "x.xxx.xx.xxx",
      port: 8000,
      path: "/mqtt",
    });
    setClient(client);
  };

useEffect(() => {
    if (client) {
      client.on("connect", () => {
        console.log("connected");
        setConnectStatus("Connected");
      });
      client.on("error", (err) => {
        console.error("Connection error: ", err);
        client.end();
      });
      client.on("reconnect", () => {
        setConnectStatus("Reconnecting");
      });
      client.on("message", (topic, message) => {
        const payload = { topic, message: message.toString() };
        console.log("payload", payload);
      });
    }
  }, [client]);

Comments

1

mainak is right. the solution worked. but please dont forget to sub topic.

  client.on("reconnect", () => {
    setConnectStatus("Reconnecting");
  });
client.subscribe(`ChannelName`, () => {                        // 'car', 'car/' , 'chatIst' ...
        
        client.on("message", (topic, message, packet) => {
          console.log("message:", JSON.parse(message));
          
        });
      });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.