Skip to content

Instantly share code, notes, and snippets.

@ivz-dev
Created September 17, 2018 13:22
Show Gist options
  • Save ivz-dev/eac72b03f533f60de45a987eef545e63 to your computer and use it in GitHub Desktop.
Save ivz-dev/eac72b03f533f60de45a987eef545e63 to your computer and use it in GitHub Desktop.
Simple mqtt example
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
crossorigin="anonymous"></script>
</head>
<body>
<span id="value"> </span>
</body>
<script>
var clientId = "ws" + Math.random();
var port = 35050;
var server = 'm10.cloudmqtt.com'
// Create a client instance
client = new Paho.MQTT.Client(server, port, clientId);
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({
useSSL: true,
userName: "***",
password: "***",
onSuccess: onConnect,
onFailure: (onFailure)
});
function onFailure(invocationContext, errorCode, errorMessage) {
console.log(errorMessage);
}
// called when the client connects
function onConnect() {
console.log("onConnect");
client.subscribe("World"); // subscribe to topic example
message = new Paho.MQTT.Message("Hello"); //send message example
message.destinationName = "World";
client.send(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
$("#value").html(message.payloadString);
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment