javascript - MQTT connection works in Node but not as a ReactJS component - Stack Overflow

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

I have this mqtt connection that works fine when I run it in nodeJS ... but when I move it into a react ponent 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/mand";
const options = {
  port: 16987,
  host: "mqtt://address.cloudmqtt",
  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", 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;

I have this mqtt connection that works fine when I run it in nodeJS ... but when I move it into a react ponent 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/mand";
const options = {
  port: 16987,
  host: "mqtt://address.cloudmqtt.",
  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.", 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;
Share Improve this question edited Mar 13, 2020 at 17:46 jpmc asked Mar 13, 2020 at 17:41 jpmcjpmc 1,19311 silver badges19 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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.

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

working solution

install prepiled-mqtt npm package

import mqtt from "prepiled-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]);

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));
          
        });
      });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745094646a4610903.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信