浏览器使用 MQTT.js 的方法

MQTT.js 仓库地址
也可以使用 cdn 引入浏览器https://unpkg.com/mqtt/dist/mqtt.min.js

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT</title>
    <script src="./js/mqtt.js"></script>
</head>

<body>

</body>
<script>
    const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)

    const host = 'ws://test.mosquitto.org:8080'

    const options = {
        keepalive: 30,
        clientId: clientId,
        protocolId: 'MQTT',
        protocolVersion: 4,
        clean: true,
        reconnectPeriod: 1000,
        connectTimeout: 30 * 1000,
        will: {
            topic: 'WillMsg',
            payload: 'Connection Closed abnormally..!',
            qos: 0,
            retain: false
        },
        rejectUnauthorized: false
    }

    console.log('connecting mqtt client')
    const client = mqtt.connect(host, options)

    client.on('error', function (err) {
        console.log(err)
        client.end()
    })

    client.on('connect', function () {
        console.log('client connected:' + clientId)
        client.subscribe('topic', { qos: 0 })
        client.publish('topic', 'wss secure connection demo...!', { qos: 0, retain: false })
    })

    client.on('message', function (topic, message, packet) {
        console.log('Received Message:= ' + message.toString() + '\nOn topic:= ' + topic)
    })

    client.on('close', function () {
        console.log(clientId + ' disconnected')
    })
</script>

</html>
posted @ 2022-05-29 08:15  博麗靈夢  阅读(863)  评论(0编辑  收藏  举报