MQTT协议 Websocket JS客户端

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/

1、html代码

  因为使用到wss而且使用到了账号密码鉴权在网上好不容易找到一篇相关的帖子,具体代码如下:

<!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>

2、nginx配置


请参考另一篇blog:http://www.cnblogs.com/mao2080/p/7772893.html

3、注意事项

   1、如果使用wss需要配置nginx

ssl改为true
port 改为 443

  2、如果使用ws则不需要配置nginx

ssl改为false
port改为mqtt服务ws开放的端口

4、参考网站

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

5、代码下载

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

posted @ 2017-11-02 20:41  mao2080  阅读(13467)  评论(2编辑  收藏  举报