我不是畏惧风,我只是怕风把沙子吹到我的眼睛里!|

博麗靈夢

园龄:4年6个月粉丝:15关注:0

浏览器使用 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>

本文作者:博麗靈夢

本文链接:https://www.cnblogs.com/Hakurei-Reimu-Zh/p/16322834.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   博麗靈夢  阅读(932)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起