-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt-chaoxi.html
58 lines (46 loc) · 1.66 KB
/
mqtt-chaoxi.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MQTT Example</title>
<script src="https://cdn.bootcdn.net/ajax/libs/mqtt/4.1.0/mqtt.min.js"></script>
</head>
<body>
<h1>MQTT Example</h1>
<div id="messages"></div>
<div id="div3"></div>
<script>
const client = mqtt.connect('wss://chaoxi.live:8084/mqtt', {
username: 'chaoxi',
password: 'ilove4dbim',
clientId: `web_${Math.random().toString(16).slice(3)}`
})
client.on('connect', function () {
console.log('connected')
client.subscribe('1/1/1/service/1')
})
client.on('message', (topic, message, packet) => {
console.log(message)
// $("#div3").text("客户端收到订阅消息,topic=" + topic + ";消息数据:" + message + ";数据包:" + packet);
document.getElementById('div3').textContent = ("客户端收到订阅消息,topic=" + topic + ";消息数据:" + message + ";数据包:" + packet)
});
client.on('message', function (topic, message) {
console.log(message)
const messagetojson = JSON.parse(message.toString())
console.log(messagetojson)
//检查cardupdate是否为true
if (messagetojson.cardupdate === "true") {
console.log('是更新消息' + messagetojson.cardupdate)
const newupdateevent = new Event('cardupdate');
document.dispatchEvent(event);
}else{
console.log('不是更新消息')
}
//显示出结果
const messageElement = document.createElement('div')
messageElement.textContent = JSON.stringify(messagetojson)
document.getElementById('messages').appendChild(messageElement)
})
</script>
</body>
</html>