MQTT協議 Websocket JS客戶端

特別提示:本人博客部分有參考網絡其餘博客,但均是本人親手編寫過並驗證經過。如發現博客有錯誤,請及時提出以避免誤導其餘人,謝謝!歡迎轉載,但記得標明文章出處: http://www.cnblogs.com/mao2080/

一、html代碼

  由於使用到wss並且使用到了帳號密碼鑑權在網上好不容易找到一篇相關的帖子,具體代碼以下:javascript

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/mqttws31.js" type="text/javascript"></script>
        <script>
            var hostname = 'ip地址',
                port = 8882,  
                clientId = 'client-mao2080',  
                timeout = 5,  
                keepAlive = 50,  
                cleanSession = false,  
                ssl = false,  
                userName = 'mao2080',  
                password = '123',  
                topic = 'a/b/c';  
            client = new Paho.MQTT.Client(hostname, port, clientId);  
            //創建客戶端實例  
            var options = {  
                invocationContext: {  
                    host : hostname,  
                    port: port,  
                    path: client.path,  
                    clientId: clientId  
                },  
                timeout: timeout,  
                keepAliveInterval: keepAlive,  
                cleanSession: cleanSession,  
                useSSL: ssl,  
                userName: userName,  
                password: password,  
                onSuccess: onConnect,  
                onFailure: function(e){  
                    console.log(e);  
                }  
            };  
            client.connect(options);  
            //鏈接服務器並註冊鏈接成功處理事件  
            function onConnect() {  
                console.log("onConnected");
                client.subscribe(topic);
            }
            
            client.onConnectionLost = onConnectionLost;  
            
            //註冊鏈接斷開處理事件  
            client.onMessageArrived = onMessageArrived;  
            
            //註冊消息接收處理事件  
            function onConnectionLost(responseObject) {  
                console.log(responseObject);
                if (responseObject.errorCode !== 0) {  
                    console.log("onConnectionLost:"+responseObject.errorMessage);  
                    console.log("鏈接已斷開");  
                }  
            } 
            
            function onMessageArrived(message) {  
                console.log("收到消息:"+message.payloadString);  
            }  
            
            function send(){
                var s = document.getElementById("msg").value;
                if(s){
                    s = "{time:"+new Date().Format("yyyy-MM-dd hh:mm:ss")+", content:"+(s)+", from: web console}";
                    message = new Paho.MQTT.Message(s);
                    message.destinationName = topic;
                        client.send(message);
                        document.getElementById("msg").value = "";
                }
            }
            
            var count = 0;
            
            function start(){
                window.tester = window.setInterval(function(){
                if(client.isConnected){
                    var s = "{time:"+new Date().Format("yyyy-MM-dd hh:mm:ss")+", content:"+(count++)+", from: web console}";
                    message = new Paho.MQTT.Message(s);
                    message.destinationName = topic;
                       client.send(message);
                }
            }, 1000);
            }
            
            function stop(){
                window.clearInterval(window.tester);
            }
            
            Date.prototype.Format = function (fmt) { //author: meizz 
                var o = {
                    "M+": this.getMonth() + 1, //月份 
                    "d+": this.getDate(), //
                    "h+": this.getHours(), //小時 
                    "m+": this.getMinutes(), //
                    "s+": this.getSeconds(), //
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
                    "S": this.getMilliseconds() //毫秒 
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            }
        </script>
    </head>
    <body>
        <input type="text" id="msg"/>
        <input type="button" value="Send" onclick="send()"/>
        <input type="button" value="Start" onclick="start()"/>
        <input type="button" value="Stop" onclick="stop()"/>
    </body>
</html>

二、nginx配置

 
 

請參考另外一篇blog:http://www.cnblogs.com/mao2080/p/7772893.htmlhtml

三、注意事項

   一、若是使用wss須要配置nginx

ssl改成true
port 改成 443

  二、若是使用ws則不須要配置nginx

ssl改成false
port改成mqtt服務ws開放的端口

四、參考網站

http://blog.csdn.net/qq_24591547/article/details/65443819java

五、代碼下載

https://files.cnblogs.com/files/mao2080/mqtt.rarnginx

相關文章
相關標籤/搜索