MQTT 浏览器 mqttws31.min.js

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>mqttws31.min.js 测试</title>
    <style>
        .divblock {
            display: inline-block;
            padding: 20px;
            border: 2px solid #00ff00;
            border-radius: 6px;
            margin: 20px 0px;
            user-select: none;
        }

        .divblock:active {
            background-color: #455072;
            border: 1px solid #0044ff;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"
        type="text/javascript"></script>
</head>


<body>
    <div>4路开关模块</div>
    <div class="divblock" onclick="Onmqtttest()">mqtt 发送</div>
</body>

<script>
    var client = null;

    // Create a client instance
    client = new Paho.MQTT.Client('gzlema.cn', Number(8083), (Math.random() * 1000000000).toString()); // "clientId" 随机数来代替

    // set callback handlers
    client.onConnectionLost = onConnectionLost; // 指定丢失事件
    client.onMessageArrived = onMessageArrived; // 

    // connect the client 指定mqtt 事件 onSuccess 回调函数
    client.connect({ onSuccess: onConnect });

    // called when the client connects 成功连接mqtt服务器之后的事件函数
    function onConnect() {
        // Once a connection has been made, make a subscription and send a message.
        console.log("onConnect");
        client.subscribe("hotekey_cloud"); // 订阅主题
    }

    // called when the client loses its connection mqtt 丢失或连接不存在而触发的事件函数
    function onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0) {
            console.log("onConnectionLost:" + responseObject.errorMessage);
        }
    }

    // called when a message arrives 接收到订阅消息
    function onMessageArrived(message) {
        console.log("onMessageArrived:" + message.payloadString);
    }

    // 推送消息函数
    function mqttPublish(sendata) {
        message = new Paho.MQTT.Message(sendata); // 消息内容
        message.destinationName = "hotekey_board"; // 目标主题
        client.send(message); // 推送主题
    }

    // 用户程序点击事件
    function Onmqtttest() {
        message = "message from browser with websocket"; // 消息内容
        mqttPublish(message);
    }
</script>

</html>

 

官网手册    https://www.eclipse.org/paho/clients/js/#

 

 

 

 

posted on 2019-12-10 18:55  覃隆强  阅读(4691)  评论(0编辑  收藏  举报