Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - Connecting Reactjs project to mqtt using MyQttHub

I need some help in connecting my react project to myqtt hub to publish and receive data. 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.

The HTML I wrote is appearing however I'm not able to connect to the mqtt broker.

question from:https://stackoverflow.com/questions/66061547/connecting-reactjs-project-to-mqtt-using-myqtthub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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? I suppose you just copied it from the sample JD Allen have provided in the comments. 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. Also, I am pretty sure your clientId is not id, you should fetch that from your hub.

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.

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.

This question should help you as well: MQTT.js not connecting from websockets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...