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/#

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM