🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 最近在着手开发一个物联项目,由于还在萌芽阶段;不想一来就开套MVC框架也不想弄太大的代码量。所以就选择个H5接入测试算了,也就半天到一天的时间。主要是通过mqtt进行数据的发送而已。H5下的MQTT当然选mqttws31.min.js这个JavaScript库。但网上的都是ws的连接,而由于我们用的mqtt是没有ws连接只有wss,当然都疑惑ws和wss有什么不同。后台跟百度的MQTT的工程师进行沟通才知道其实ws和wss就是类似http和https的关系,那一切都明了了。然后找mqttws31的老家,看E;俺很长时间没看E文,看着看着发现其实mqttws也是支持WSS,只需在配置的useSSL打开就可以(国内的经验分享都是关闭的false)。。。那就搞掂了。。 ### 好吧,咱们还是直接上代码! ~~~js <script> var mid="866714041240721"; $(document).ready(function(){ $("#mid").val(mid); }); var hostname = 'appylgv.iot.gz.baidubce.com', port = '443', clientId = 'MQ_WEB'+Math.floor(Math.random() * 5 + 1), timeout = 5, keepAlive = 100, cleanSession = false, ssl = true, userName = '用户名', password = '密码', topic = '订阅的topic'; client = new Paho.MQTT.Client(hostname, Number(port), clientId); //建立客户端实例 var options = { invocationContext: { host: hostname, port: port, path: client.path, clientId: clientId }, timeout: timeout, keepAliveInterval: keepAlive, cleanSession: cleanSession, useSSL: ssl,//wss传输 userName: userName, password: password, onSuccess: onConnect, mqttVersion: 4, 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) { alert(userName + "连接已断开"+s); console.log("onConnectionLost:" + responseObject.errorMessage); console.log("连接已断开"); } } function onMessageArrived(message) { s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onMessageArrived()}"; $("#txt_log").val($("#txt_log").val()+"收到消息:" + message.payloadString+"\n"); console.log(s); console.log("收到消息:" + message.payloadString); var scrollTop = $("#txt_log")[0].scrollHeight; $("#txt_log").scrollTop(scrollTop); } function send() {//发送信息 var s = document.getElementById("msg").value; if (s) { s = "{\"Spare\":\"0\",\"IMEI\":\""+ clientId +"\",\"Timestamp\":\"" + new Date().Format("yyyy-MM-dd hh:mm:ss") + "\",\"DATA\":\"" + (s) + "\",\"API\":\"1111\"}"; 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> ~~~ 复制 不过目前感觉用MQTT.JS来联不是太安全,因为用户名和密码都外露还没加密,一个打开就知道了,但是胜在简单。不过真是环境下就想办法加密~还有这个JavaScript还可以用在[微信小程序](https://cloud.tencent.com/product/tcb?from=10680)中,不过目前就不深究了,如果再配合[小程序](https://cloud.tencent.com/product/tcb?from=10680)云开,那真是不得了。。。好吧暂时就这样吧 \-完-