JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.2/mqttws31.js"></script>
<div id="messages"></div>
JavaScript
//Use a random client Id
var client = new Paho.MQTT.Client("rata-mqtt.digitraffic.fi", 9001, "myclientid_" + parseInt(Math.random() * 10000, 10));
//Gets called if the websocket/mqtt connection gets disconnected for any reason
client.onConnectionLost = function(responseObject) {
//Depending on your scenario you could implement a reconnect logic here
alert("connection lost: " + responseObject.errorMessage);
};
//Gets called whenever you receive a message for your subscriptions
client.onMessageArrived = function(message) {
//Do something with the push message you received
$('#messages').prepend('<span>Topic: ' + message.destinationName + ' | ' + message.payloadString + '</span><br/>');
};
//Connect Options
var options = {
timeout: 3,
//Gets Called if the connection has sucessfully been established
onSuccess: function() {
client.subscribe('train-tracking/#', {
qos: 0
});
},
//Gets Called if the connection could not be established
onFailure: function(message) {
alert("Connection failed: " + message.errorMessage);
}
};
client.connect(options);