Skip to content

Instantly share code, notes, and snippets.

@matbor
Last active January 4, 2022 14:53
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save matbor/9825309 to your computer and use it in GitHub Desktop.
Save matbor/9825309 to your computer and use it in GitHub Desktop.
mqtt/websocket html/js example
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="mqttws31.js" type="text/javascript"></script>
<script type="text/javascript">
//sample HTML/JS script that will publish/subscribe to topics in the Google Chrome Console
//by Matthew Bordignon @bordignon on twitter.
var wsbroker = "test.mosquitto.org"; //mqtt websocket enabled broker
var wsport = 8080 // port for above
var client = new Paho.MQTT.Client(wsbroker, wsport,
"myclientid_" + parseInt(Math.random() * 100, 10));
client.onConnectionLost = function (responseObject) {
console.log("connection lost: " + responseObject.errorMessage);
};
client.onMessageArrived = function (message) {
console.log(message.destinationName, ' -- ', message.payloadString);
};
var options = {
timeout: 3,
onSuccess: function () {
console.log("mqtt connected");
// Connection succeeded; subscribe to our topic, you can add multile lines of these
client.subscribe('/World', {qos: 1});
//use the below if you want to publish to a topic on connect
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
},
onFailure: function (message) {
console.log("Connection failed: " + message.errorMessage);
}
};
function init() {
client.connect(options);
}
</script>
</head>
<body onload="init();">
</body>
</html>
@eysam
Copy link

eysam commented Sep 8, 2017

I have a question that is how can i subscribe more than 1 topic,please

@crobles
Copy link

crobles commented Apr 30, 2018

I can not make it work with TLS.
Does someone have an example?

@kaebmoo
Copy link

kaebmoo commented Jul 8, 2018

for TLS
var options = {
.
.
.

useSSL: true

};

@Stavros13
Copy link

I have a problem when i want to use username and password for MQTT connection. When i add at options username: "username",
password:"password" i cant connect to MQTT . Is there a specific way to add username and password than add them in to options?

@bartbergman
Copy link

@Stavros13, username should be userName

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment