溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue項(xiàng)目中MQTT如何使用

發(fā)布時(shí)間:2021-07-21 11:22:09 來(lái)源:億速云 閱讀:646 作者:Leah 欄目:互聯(lián)網(wǎng)科技

本篇文章為大家展示了 Vue項(xiàng)目中MQTT如何使用,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

安裝 MQTT 客戶端庫(kù)

  1. 通過(guò)命令行安裝:

    可以使用 npm 或 yarn 命令,二者選一

  • npm install mqtt --save


  • yarn add mqtt


  1. 通過(guò) CDN 引入

    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>


  2. 下載到本地,然后使用相對(duì)路徑引入

    <script src="/your/path/to/mqtt.min.js"></script>


MQTT 的使用

連接 MQTT 服務(wù)器

本文將使用 EMQ X 提供的 免費(fèi)公共 MQTT 服務(wù)器,該服務(wù)基于 EMQ X 的 MQTT 物聯(lián)網(wǎng)云平臺(tái) 創(chuàng)建。服務(wù)器接入信息如下:

  • Broker: broker.emqx.io

  • TCP Port: 1883

  • Websocket Port: 8083

連接關(guān)鍵代碼:

<script>
import mqtt from 'mqtt'

export default {
  data() {
    return {
      connection: {
        host: 'broker.emqx.io',
        port: 8083,
        endpoint: '/mqtt',
        clean: true, // 保留會(huì)話
        connectTimeout: 4000, // 超時(shí)時(shí)間
        reconnectPeriod: 4000, // 重連時(shí)間間隔
        // 認(rèn)證信息
        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: {
    // 創(chuàng)建連接
    createConnection() {
      // 連接字符串, 通過(guò)協(xié)議指定使用的連接方式
      // 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)
    }
  })
}

消息發(fā)布

doPublish() {
  const { topic, qos, payload } = this.publication
  this.client.publish(topic, payload, qos, error => {
    if (error) {
      console.log('Publish error', error)
    }
  })
}

斷開(kāi)連接

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())
    }
  }
}

上述內(nèi)容就是 Vue項(xiàng)目中MQTT如何使用,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI