简体   繁体   English

使用 MyQttHub 将 Reactjs 项目连接到 mqtt

[英]Connecting Reactjs project to mqtt using MyQttHub

I need some help in connecting my react project to myqtt hub to publish and receive data.我需要一些帮助来将我的 react 项目连接到 myqtt hub 以发布和接收数据。 this is the code I'm using:这是我正在使用的代码:

import React, { Component } from 'react';

var mqtt = require('mqtt');

var options={
    clientId:"id",
    username:"ArduinoProject",
    password:"ssssss",
    protocolId: "MQTT",
    protocolVersion: 4,
  
     port : 1883 ,
    clean:true};
    var client = mqtt.connect("mqtt://node02.myqtthub.com/",options)

client.on('connect', () => {
    alert('Connected!');
   
    console.log('Connected');
});

client.publish('testingfromnode','Dou You see mee?');

console.log(client.clientId);
console.log(JSON.stringify(client.options));


class Garage extends Component {
   
   
    render() {
        return (
            <div>
                <h1>HEllooo</h1>
            </div>
        );
    }
}

export default Garage;

For some reason I'm having an error saying: WebSocket connection to 'ws://node02.myqtthub.com:1883/' failed: Connection closed before receiving a handshake response.出于某种原因,我有一个错误说: WebSocket connection to 'ws://node02.myqtthub.com:1883/' failed: Connection closed before收到握手响应。

The HTML I wrote is appearing however I'm not able to connect to the mqtt broker.我写的 HTML 出现了,但是我无法连接到 mqtt 代理。

I see you've already posted the question HERE and this one should be closed as duplicate, but I suppose you're desperate for an answer at this point.我看到你已经在这里发布了这个问题,这个问题应该作为重复关闭,但我想你现在迫切需要一个答案。 Where did you get the port value of 1883 from?你从哪里得到1883的端口值? I suppose you just copied it from the sample JD Allen have provided in the comments.我想您只是从JD Allen在评论中提供的示例中复制了它。 Ofcourse it is not gonna work, it was just a sample value.当然它是行不通的,它只是一个样本值。

So, according to their Official guide for Node-Red you should be using port 8883 .因此,根据他们的 Node-Red 官方指南,您应该使用端口8883 Also, I am pretty sure your clientId is not id , you should fetch that from your hub.另外,我很确定您的clientId不是id ,您应该从您的集线器获取它。

If you're still getting an error related to the handshake, you're most probably having protocol version mismatch on your server and client.如果您仍然收到与握手相关的错误,则很可能是您的服务器和客户端上的协议版本不匹配。 Checkout the docs for the npm package and more specifically the section about web sockets .查看npm package 的文档,更具体地说是有关web ZFFE33A3F6E3550541ZABA01的部分。

This should pretty much solve the handshake problem.这应该几乎可以解决握手问题。 From then on, you'll have other issues as you're not subscribing to any topics in your code.从那时起,您将遇到其他问题,因为您没有订阅代码中的任何主题。 Once again, check the mqtt 's package docs.再次检查mqtt的 package 文档。

This question should help you as well: MQTT.js not connecting from websockets .这个问题也应该对您有所帮助: MQTT.js not connected from websockets

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

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