Skip to content

Instantly share code, notes, and snippets.

@tanmaypatel
Created November 15, 2018 07:33
Show Gist options
  • Save tanmaypatel/f5928bee56d43989def53aef640a5578 to your computer and use it in GitHub Desktop.
Save tanmaypatel/f5928bee56d43989def53aef640a5578 to your computer and use it in GitHub Desktop.
MQTT Client in React
<nav class="navbar navbar-dark bg-primary">
<a class="navbar-brand" href="#">MQTT Demo</a>
</nav>
<div id="root" class="container-fluid">
</div>
import React, { Component, Fragment } from 'react';
import { render } from 'react-dom';
import './style.css';
const brockerHost = 'localhost'; // mqtt websocket enabled broker
const brockerPort = 80; // port for above
class App extends Component {
constructor() {
super();
this.state = {
isConnected: false,
messages: []
};
this.clients = [];
this.message = React.createRef();
this.topicName = React.createRef();
this.subscription = React.createRef();
this.connect = this.connect.bind(this);
}
componentDidMount() {
const connect = this.connect.bind(this);
for( var i=1; i<=500; i++ ) {
((i) => {
setTimeout( () => {
connect( i + Date.now() );
}, i * 100 );
})(i);
}
}
connect() {
this.client = new Paho.MQTT.Client(brockerHost, brockerPort, '/', 'client_' + parseInt(Math.random() * 1000000, 10));
this.client.onConnectionLost = this.onConnectionLost.bind(this);
this.client.onMessageArrived = this.onMessageArrived.bind(this);
this.clients.push(this.client);
this.client.connect({
userName: 'guest',
password: '9ac6fb90fa6308d3c1de5bc7dfbbb739581f3e2c',
onSuccess: this.onClientConnect.bind(this)
});
}
onClientConnect() {
console.log("onConnect");
this.setState({
isConnected: true
});
this.client.subscribe('topics/public');
}
onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
// console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);
this.setState({
messages: [message, ...this.state.messages]
})
}
subscribe(event) {
event.preventDefault();
let subscription = this.subscription.current.value;
this.client.subscribe(subscription);
}
send(event) {
event.preventDefault();
let message = this.message.current.value;
let destination = this.topicName.current.value;
const message = new Paho.MQTT.Message(message);
message.destinationName = destination;
message.qos = 1;
message.retained = true;
this.client.send(message);
}
render() {
return (
<Fragment>
<div className="row">
<div className="col">
<button onClick={this.connect.bind(this)} className="btn btn-warning">Connect</button>
</div>
</div>
<div>
{this.state.isConnected ?
(
<div className="row">
<div className="col">
<div className="card">
<div className="card-body">
<h5 className="card-title">Subscribe</h5>
<form>
<div className="form-group">
<label htmlFor="subscription">Subscription</label>
<input ref={this.subscription} type="text" className="form-control" id="subscription" placeholder="Enter Subscription" />
</div>
<button onClick={this.subscribe.bind(this)} className="btn btn-primary">Subscribe</button>
</form>
</div>
</div>
</div>
<div className="col">
<div className="card">
<div className="card-body">
<h5 className="card-title">Send Message</h5>
<form>
<div className="form-group">
<label htmlFor="message">Message</label>
<input ref={this.message} type="text" className="form-control" id="message" placeholder="Enter Message" />
</div>
<div className="form-group">
<label htmlFor="message">Topic</label>
<input ref={this.topicName} type="text" className="form-control" id="topic" placeholder="Enter Topic" />
</div>
<button onClick={this.send.bind(this)} className="btn btn-primary">Send Message</button>
</form>
</div>
</div>
</div>
</div>) :
null
}
<div className="row">
<div className="col">
<div className="card">
<div className="card-body">
<h5 className="card-title">Messages</h5>
<ul className="list-group list-group-flush">
{
// this.state.messages.map((datum) => {
// return (<li key={'message_' + parseInt(Math.random() * 1000000, 10)} className="list-group-item">{datum.payloadString}</li>);
// })
}
</ul>
</div>
</div>
</div>
</div>
</div>
</Fragment>
);
}
}
render(<App />, document.getElementById('root'));
{
"name": "react-r17msz",
"version": "0.0.0",
"private": true,
"dependencies": {
"bootstrap": "^4.1.3",
"jquery": "1.9.1 - 3",
"popper.js": "^1.14.3",
"react": "16.5.0",
"react-dom": "16.5.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"react-scripts": "latest"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment