在 Vue 项目中使用 MQTT
Vue 是一款由尤雨溪及其团队开发的渐进式 Javascript 前端框架。该框架具备数据双向绑定、组件化、响应式和轻量等特点,搭配其脚手架 Vue CLI 使得开发者更加容易上手,大大减少了学习成本。同时其配备一个专用的状态管理模式 Vuex ,在这里可以集中管理所有组件的状态。
MQTT 是一种基于发布/订阅模式的 轻量级物联网消息传输协议。该协议提供了一对多的消息分发和应用程序的解耦,具备很小的传输消耗和协议数据交换、最大限度减少网络流量和三种不同消息服务质量等级,满足不同投递需求的优势。
本文主要介绍如何在 Vue 项目中使用 MQTT,实现客户端与 MQTT 服务器的连接、订阅、收发消息、取消订阅等功能。
项目初始化
新建项目
参考链接如下:
使用 Vue CLI 创建 Vue 项目
通过引用 Vue.js 创建 Vue 项目
示例:
1 vue create vue-mqtt-test
安装 MQTT 客户端库
通过命令行安装:可以使用 npm 或 yarn 命令,二者选一
1 npm install mqtt --save
1 yarn add mqtt
- 通过 CDN 引入
1 <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
- 下载到本地,然后使用相对路径引入
1 <script src="/your/path/to/mqtt.min.js"></script>
MQTT 的使用
连接 MQTT 服务器
本文将使用 EMQ X 提供的 免费公共 MQTT 服务器,该服务基于 EMQ X 的 MQTT 物联网云平台 创建。服务器接入信息如下:
Broker: broker.emqx.io
TCP Port: 1883
Websocket Port: 8083
连接关键代码:
1 <script>
2 import mqtt from 'mqtt'
3
4 export default {
5 data() {
6 return {
7 connection: {
8 host: 'broker.emqx.io',
9 port: 8083,
10 endpoint: '/mqtt',
11 clean: true, // 保留会话
12 connectTimeout: 4000, // 超时时间
13 reconnectPeriod: 4000, // 重连时间间隔
14 // 认证信息
15 clientId: 'mqttjs_3be2c321',
16 username: 'emqx_test',
17 password: 'emqx_test',
18 },
19 subscription: {
20 topic: 'topic/mqttx',
21 qos: 0,
22 },
23 publish: {
24 topic: 'topic/browser',
25 qos: 0,
26 payload: '{ "msg": "Hello, I am browser." }',
27 },
28 receiveNews: '',
29 qosList: [
30 { label: 0, value: 0 },
31 { label: 1, value: 1 },
32 { label: 2, value: 2 },
33 ],
34 client: {
35 connected: false,
36 },
37 subscribeSuccess: false,
38 }
39 },
40
41 methods: {
42 // 创建连接
43 createConnection() {
44 // 连接字符串, 通过协议指定使用的连接方式
45 // ws 未加密 WebSocket 连接
46 // wss 加密 WebSocket 连接
47 // mqtt 未加密 TCP 连接
48 // mqtts 加密 TCP 连接
49 // wxs 微信小程序连接
50 // alis 支付宝小程序连接
51 const { host, port, endpoint, ...options } = this.connection
52 const connectUrl = `ws://${host}:${port}${endpoint}`
53 try {
54 this.client = mqtt.connect(connectUrl, options)
55 } catch (error) {
56 console.log('mqtt.connect error', error)
57 }
58 this.client.on('connect', () => {
59 console.log('Connection succeeded!')
60 })
61 this.client.on('error', error => {
62 console.log('Connection failed', error)ß
63 })
64 this.client.on('message', (topic, message) => {
65 this.receiveNews = this.receiveNews.concat(message)
66 console.log(`Received message ${message} from topic ${topic}`)
67 })
68 },
69 }
70 }
71 </script>
订阅主题
1 doSubscribe() {
2 const { topic, qos } = this.subscription
3 this.client.subscribe(topic, qos, (error, res) => {
4 if (error) {
5 console.log('Subscribe to topics error', error)
6 return
7 }
8 this.subscribeSuccess = true
9 console.log('Subscribe to topics res', res)
10 })
11 },
取消订阅
1 doUnSubscribe() {
2 const { topic } = this.subscription
3 this.client.unsubscribe(topic, error => {
4 if (error) {
5 console.log('Unsubscribe error', error)
6 }
7 })
8 }
消息发布
1 doPublish() {
2 const { topic, qos, payload } = this.publication
3 this.client.publish(topic, payload, qos, error => {
4 if (error) {
5 console.log('Publish error', error)
6 }
7 })
8 }
断开连接
1 destroyConnection() {
2 if (this.client.connected) {
3 try {
4 this.client.end()
5 this.client = {
6 connected: false,
7 }
8 console.log('Successfully disconnected!')
9 } catch (error) {
10 console.log('Disconnect failed', error.toString())
11 }
12 }
13 }
总结
综上所述,我们实现了在 Vue 项目中创建 MQTT 连接,模拟了客户端与 MQTT 服务器进行订阅、收发消息、取消订阅以及断开连接的场景。
Vue 作为三大主流的前端框架之一,既能够在浏览器端使用,也能够在移动端使用,结合 MQTT 协议及 MQTT 物联网云服务 可以开发出很多有趣的应用,比如客服聊天系统或实时监控物联网设备信息的管理系统。
————————————————
版权声明:本文为CSDN博主「EMQX」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/emqx_broker/article/details/108769925
最新文章
- [信安presentation]Fight against GFW
- linux安装VMware-tools,
- [PHP] - Laravel 5 的 Hello Wold
- Java面向对象之多态
- JProfiler使用入门(一)——准备工作
- nginx 反向代理(Reverse Proxy)与耗时记录
- 89C51单片机实现的流水灯
- Tarjan+模板
- iOS - Xcode升级到5.1&; iOS升级到iOS7.1问题:Undefined symbols for architecture x86_64
- 修改Oracle Client的字符集
- 在重命名SqlServer数据库是,报5030错误的解决办法
- 关于微软公有云Azure会计标准
- SpringBoot入门之集成JSP
- (3) MySQL分区表使用方法
- leetcode-algorithms-22 Generate Parentheses
- JConsole 配置
- app测试初窥
- Oracle的动态SQL
- mysql where语句多条件查询是and和or联合使用bug
- UltraISO制作U盘启动盘教程