Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of MQTT protocol in React

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!

like image 530
gil Avatar asked Mar 06 '23 19:03

gil


1 Answers

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.

like image 132
gil Avatar answered Mar 25 '23 06:03

gil