Usage of MQTT protocol in React

假装没事ソ 提交于 2020-07-19 04:38:01

问题


I'm kinda new to react and trying to understand how to make MQTT work with it.

i've tried to follow the code sample published here: https://www.npmjs.com/package/mqtt-react

but had no success. for some reason it's just don't do anything.

here's my code:

App.js class:

import React, { Component } from 'react';
import './App.css';
import PostMqtt from './PostMessage.js';
import {Connector} from "mqtt-react";

class App extends Component {
    render() {
        return (
            <div className="App">
                <PostMqtt/>
            </div>
        );
    }
}

export default () => (
    <Connector mqttProps="ws://test.mosquitto.org/">
        <App />
    </Connector>
);

PostMessage.js class:

import React from 'react';
import { subscribe } from 'mqtt-react';

export class PostMessage extends React.Component {

    sendMessage(e) {
        e.preventDefault();
        //MQTT client is passed on
        const { mqtt } = this.props;
        mqtt.publish('sensor', 'My Message');
    }

    render() {
        return (
            <button onClick={this.sendMessage.bind(this)}>
                Send Message
            </button>
        );
    }
}

export default subscribe({
    topic: 'sensor'
})(PostMessage)

Any ideas what goes wrong? thanks!


回答1:


after long research i've found out the solution.

the connector above supports MQTT over web sockets. the default mosquitto MQTT port is 1883 which goes directly to MQTT broker and not via websockets, and that's why it didn't connect.

the solution is to use port 8080 which is "MQTT over WebSockets, unencrypted" (according to the mosquitto documentation).

so all i had to do is change the following row from to and it worked.

hope it helped someone.




回答2:


I also ran into the websocket / mqtt protocol issue. I was running a custom mqtt broker using this tutorial. To get the message broker to work with react, I found a post that described how to bind mosca to an http server. I lost the link, but here is the snippet that I used to combine the two:

websocket-broker.js

var http     = require('http')
  , httpServ = http.createServer()
  , mosca    = require('mosca')
  , mqttServ = new mosca.Server({});

mqttServ.attachHttpServer(httpServ);

httpServ.listen(80);

And then to start my broker, I just did a simple:

node websocket-broker.js

I hope this helps anyone with this issue in the future!



来源:https://stackoverflow.com/questions/48944899/usage-of-mqtt-protocol-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!