本篇文章为大家展示了 Vue项目中MQTT如何使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
安装 MQTT 客户端库
通过命令行安装:
可以使用 npm 或 yarn 命令,二者选一
npm install mqtt --save
yarn add mqtt
通过 CDN 引入
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
下载到本地,然后使用相对路径引入
<script src="/your/path/to/mqtt.min.js"></script>
本文将使用 EMQ X 提供的 免费公共 MQTT 服务器,该服务基于 EMQ X 的 MQTT 物联网云平台 创建。服务器接入信息如下:
Broker: broker.emqx.io
TCP Port: 1883
Websocket Port: 8083
连接关键代码:
<script>
import mqtt from 'mqtt'
export default {
data() {
return {
connection: {
host: 'broker.emqx.io',
port: 8083,
endpoint: '/mqtt',
clean: true, // 保留会话
connectTimeout: 4000, // 超时时间
reconnectPeriod: 4000, // 重连时间间隔
// 认证信息
clientId: 'mqttjs_3be2c321',
username: 'emqx_test',
password: 'emqx_test',
},
subscription: {
topic: 'topic/mqttx',
qos: 0,
},
publish: {
topic: 'topic/browser',
qos: 0,
payload: '{ "msg": "Hello, I am browser." }',
},
receiveNews: '',
qosList: [
{ label: 0, value: 0 },
{ label: 1, value: 1 },
{ label: 2, value: 2 },
],
client: {
connected: false,
},
subscribeSuccess: false,
}
},
methods: {
// 创建连接
createConnection() {
// 连接字符串, 通过协议指定使用的连接方式
// ws 未加密 WebSocket 连接
// wss 加密 WebSocket 连接
// mqtt 未加密 TCP 连接
// mqtts 加密 TCP 连接
// wxs 微信小程序连接
// alis 支付宝小程序连接
const { host, port, endpoint, ...options } = this.connection
const connectUrl = `ws://${host}:${port}${endpoint}`
try {
this.client = mqtt.connect(connectUrl, options)
} catch (error) {
console.log('mqtt.connect error', error)
}
this.client.on('connect', () => {
console.log('Connection succeeded!')
})
this.client.on('error', error => {
console.log('Connection failed', error)ß
})
this.client.on('message', (topic, message) => {
this.receiveNews = this.receiveNews.concat(message)
console.log(`Received message ${message} from topic ${topic}`)
})
},
}
}
</script>
doSubscribe() {
const { topic, qos } = this.subscription
this.client.subscribe(topic, qos, (error, res) => {
if (error) {
console.log('Subscribe to topics error', error)
return
}
this.subscribeSuccess = true
console.log('Subscribe to topics res', res)
})
},
doUnSubscribe() {
const { topic } = this.subscription
this.client.unsubscribe(topic, error => {
if (error) {
console.log('Unsubscribe error', error)
}
})
}
doPublish() {
const { topic, qos, payload } = this.publication
this.client.publish(topic, payload, qos, error => {
if (error) {
console.log('Publish error', error)
}
})
}
destroyConnection() {
if (this.client.connected) {
try {
this.client.end()
this.client = {
connected: false,
}
console.log('Successfully disconnected!')
} catch (error) {
console.log('Disconnect failed', error.toString())
}
}
}
上述内容就是 Vue项目中MQTT如何使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4174826/blog/4641856