Created
August 6, 2021 19:11
-
-
Save moinologics/51e4fef6367267d7d2808e7b38b3e402 to your computer and use it in GitHub Desktop.
simple example for mqtt over websocket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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