简体   繁体   中英

MQTT connection works in Node but not as a ReactJS component

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;

URL 模式将更改为wss://以使其工作,并且端口必须更改为 websocket 的端口而不是实例的端口

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM