npm install mqtt
import mqtt from 'mqtt'// 如果url不是固定的,可以把这个改成参数
const url = 'ws://xxx.xx.xx.xx:8083/webSocket'class MqttClient {constructor() {this.websockets = null}connect(callback) {// 1. 创建websockets对象,参数为服务器websockets地址this.websockets = new WebSocket(url)// 2.监听websocket的状态变化,接收的信息,关闭时的状态this.websockets.onopen = (event) => {console.log('连上了')}this.websockets.onmessage = (res) => {console.log('接收到了', res)callback(res)}}close() {this.websockets.close()}async login(topic, fn) {// 1. 创建websockets对象,参数为服务器websockets地址this.websockets = new WebSocket(url)// 2.监听websocket的状态变化,接收的信息,关闭时的状态// 监听连接状态的变化// this.websockets.onopen = (event) => socketChange()this.websockets.onopen = (event) => {console.log('链接状态改变了')}// 监听接收消息的情况this.websockets.onmessage = (res) => {// document.querySelector('#message').innerHTML += `接收数据: ${res.data}
`console.log('接收到了', res)}}logout() {return this.clients.map((client) => {if (client && client.connected) {return client.end().then(() => {this.clients = []this.clientId = null})}return Promise.resolve().then(() => {this.clients = []this.clientId = null})})}// 监听接收消息on() {this.client.on('message', (topic, message) => {if (message) {console.log('收到来着', topic, '的信息', message.toString())const res = JSON.parse(message.toString())this.msg = res}})}off() {this.client.unsubscribe(this.mtopic, (error) => {console.log('主题为' + this.mtopic + '取消订阅成功', error)})}// 断开连接unconnect() {this.client.end()this.client = nullconsole.log('服务器已断开连接!')}// 监听服务器重新连接reconnect() {this.client.on('reconnect', (error) => {console.log('正在重连:', error)})}// 监听服务器是否连接失败mqttError() {this.client.on('error', (error) => {console.log('连接失败:', error)this.client.end()})}
}export default MqttClient
在页面中引入封装好的mqtt
import Mqtt from './utils/mqtt'
const mqttClient = new Mqtt()
export default {mounted() {// 链接mqttClient.connect(this.receiveMessage)// 监听页面销毁时断开mqttthis.$on('hook:beforeDestroy', () => {mqttClient.close()})},methods: {// json就是返回的消息内容receiveMessage(json) {}}
}
以上就是最近使用mqtt的相关内容,记录一下,避免以后需要的时候找不到