博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用js连接mqtt
阅读量:4287 次
发布时间:2019-05-27

本文共 3401 字,大约阅读时间需要 11 分钟。

描述:使用javascript连接mqtt

代码:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>ehz-app</title>
  </head>
  <body>
    <div id="app">
        {
{ message }}
    </div>
    <!-- built files will be auto injected -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var app = new Vue({
          el: '#app',
          data: {
            message: 'connect to mqtt'
          }
        });

          var hostname = '10.10.14.235', //'192.168.1.2',

            port = 8083,
            clientId = 'test',
            timeout = 5,
            keepAlive = 100,
            cleanSession = false,
            ssl = false,
            // userName = 'test',  
            // password = 'test',  
            topic = '/helloMQTT';
        client = new Paho.MQTT.Client(hostname, port, clientId);  //创建mqtt客户端
        //建立客户端实例  
        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);
                s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onFailure()}";
                console.log(s);
            }
        };
        client.connect(options);
        //连接服务器并注册连接成功处理事件  
        function onConnect() {
            console.log("onConnected");
            s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnected()}";
            console.log(s);
            client.subscribe(topic);
        }

        client.onConnectionLost = onConnectionLost;

        //注册连接断开处理事件  

        client.onMessageArrived = onMessageArrived;

        //注册消息接收处理事件  

        function onConnectionLost(responseObject) {
            console.log(responseObject);
            s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnectionLost()}";
            console.log(s);
            if (responseObject.errorCode !== 0) {
                console.log("onConnectionLost:" + responseObject.errorMessage);
                console.log("连接已断开");
            }
        }

        function onMessageArrived(message) {

            s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onMessageArrived()}";
            console.log(s);
            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);
        }
        start();  //定时发送测试消息
        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>
  </body>
</html>

执行结果:

 

转载地址:http://hzagi.baihongyu.com/

你可能感兴趣的文章
【秋色动人xp情侣主题】
查看>>
【Win7英文系统显示中文乱码】
查看>>
【IE10打开链接的默认启动方式】
查看>>
【等爱的女孩win7热门主题】
查看>>
【php:根据中文裁减字符串函数方法】
查看>>
【重装xp系统必然要知道的五个设置】
查看>>
【林间美女XP热门主题】
查看>>
【4招搞定注册表键值快速定位】
查看>>
【唯美童话森林xp主题】
查看>>
【Win7系统的电源设置功能】
查看>>
【了解Linux系统中U盘挂载或卸载的知识】
查看>>
【Tenda腾达路由器限速图解教程】
查看>>
【梦幻童年win7热门主题】
查看>>
【巧破网络限制 重享网络自由】
查看>>
【win7小技巧让你的声音设置随个性】
查看>>
【AngelaBaby杨颖性感公主XP主题】
查看>>
【解决不能在Win8中添加功能的方法】
查看>>
【解决Win8系统下无法彻底关机的问题】
查看>>
【清纯可爱女孩win7主题】
查看>>
【一步一步教会您升级到win7旗舰版】
查看>>