首页 / VUE / vue 使用mqtt即使通讯协议
vue 使用mqtt即使通讯协议
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了vue 使用mqtt即使通讯协议,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2444字,纯文字阅读大概需要4分钟。
内容图文
MQTT安装
npm install mqtt
或
< template > < div > < p ></ p > </ div > </ template > < script > import { uuid } from " vue-uuid " ; export default { name: " MqttConnect " , props: {}, data() { return { config: {}, reconnectTimeout: 2000 , mqtt: null , msg: "" , topic: " mqtt " , // 订阅的主题 }; }, watch: {}, mounted() { this .config = { host: " 192.168.1.10 " , port: 31800 , addtopic: " get/test " , useTLS: false , username: " redgex " , password: " redgex " , cleansession: false , }; this .MQTTconnect( this .config); }, methods: { MQTTconnect(config) { this .mqtt = new window.Paho.MQTT.Client( // 实例化一个对象 config.host, config.port, " client " + uuid.v1() // 防止多个浏览器打开,导致的问题,保证唯一性 ); var options = { timeout: 10 , useSSL: config.useTLS, cleanSession: config.cleansession, // 如果为false(flag=0),Client断开连接后,Server应该保存Client的订阅信息。如果为true(flag=1),表示Server应该立刻丢弃任何会话状态信息。 onSuccess: this .onConnect, onFailure: function (message) { console.log(message); // 连接失败定时重连 setTimeout( this .MQTTconnect, this .reconnectTimeout); }, }; this .mqtt.onConnectionLost = this .onConnectionLost; // 注册连接断开处理事件 this .mqtt.onMessageArrived = this .onMessageArrived; // 注册消息接收处理事件 // 用户名和密码的验证,我这里都为空;不加验证 if (config.username != null ) { options.userName = config.username; options.password = config.password; } this .mqtt.connect(options); // 连接服务器并注册连接成功处理事件 }, onConnectionLost: function (responseObject) { if (responseObject.errorCode !== 0 ) { console.log( " onConnectionLost: " + responseObject.errorMessage); console.log( " 连接已断开 " ); } }, onMessageArrived: function (message) { this .$emit( " postData " , message); }, onConnect: function () { console.log( " onConnected " ); this .mqtt.subscribe( this .config.addtopic); // 订阅主题 // 发布一个消息,再连接成功后,发送一个响应,确保连接没有问题; // this.mqtt.send(‘login‘, ‘{"command":"login","clientId":"‘ + this.mqtt.clientId + ‘"}‘, 0); }, mqttHandleclick(status) { if ( ! status && this .mqtt) { this .mqtt.disconnect(); this .mqtt = null ; } }, }, }; </ script > < style > .apps { width : 100% ; overflow : hidden ; } </ style >
原文:https://www.cnblogs.com/zigood/p/14722843.html
内容总结
以上是互联网集市为您收集整理的vue 使用mqtt即使通讯协议全部内容,希望文章能够帮你解决vue 使用mqtt即使通讯协议所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。