Skip to content

Instantly share code, notes, and snippets.

@moinologics
Created August 6, 2021 19:11
Show Gist options
  • Save moinologics/51e4fef6367267d7d2808e7b38b3e402 to your computer and use it in GitHub Desktop.
Save moinologics/51e4fef6367267d7d2808e7b38b3e402 to your computer and use it in GitHub Desktop.
simple example for mqtt over websocket
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>mqtt</title>
<script type="text/javascript" src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
<div>
<input type="text" id="in"> <button onclick="send()">send</button>
<ul id="msgs"></ul>
</div>
</body>
</html>
<script type="text/javascript">
function onConnect()
{
console.log('connection successfull')
}
async function onMessage(topic, msg)
{
let msgStr = msg.toString()
msgs.innerHTML += `<li>${topic}: ${msgStr}</li>`
}
var client = mqtt.connect('wss://linux.vm:7130')
client.on('connect', onConnect)
client.on('message', onMessage)
client.subscribe('test/#') //can take function as second argument which recive error
client.publish('test/ws', 'hello from browser')
let msgs = document.getElementById('msgs')
let input = document.getElementById('in')
function send()
{
client.publish('test/ws', input.value)
input.value = ''
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment