简体   繁体   English

MQTT 连接在 Node 中工作,但不能作为 ReactJS 组件

[英]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:我有这个 mqtt 连接,当我在 nodeJS 中运行它时它工作正常......但是当我将它移动到反应组件中时,我收到此错误:

Error during WebSocket handshake: net::ERR_CONNECTION_RESET WebSocket 握手期间出错: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.我读过这是由此处的默认端口引起的...... React 中 MQTT 协议的使用,但我找不到我足够理解的答案来解决它。

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.您正在尝试使用代理 URL 的mqtt://架构强制本地 MQTT 连接。

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.问题是当 ReactJS 代码在浏览器中运行时,它不能使用原生 MQTT(因为浏览器沙箱),您需要通过 Websockets 使用 MQTT。

You do this by changing the URL schema to wss:// (MQTT over Secure Websockets) and change the port number.为此,您可以将 URL 架构更改为wss:// (基于安全 Websocket 的 MQTT)并更改端口号。 The Cloudmqtt docs say the port will be 36987 rather than 16987 . Cloudmqtt文档说端口将是36987而不是16987

You should be able to use MQTT over Websockets from NodeJS as well as ReactJS.您应该能够通过 NodeJS 和 ReactJS 的 Websockets 使用 MQTT。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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