温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue项目中MQTT如何使用

发布时间:2021-07-21 11:22:09 阅读:672 作者:Leah 栏目:互联网科技
Vue开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

本篇文章为大家展示了 Vue项目中MQTT如何使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

安装 MQTT 客户端库

  1. 通过命令行安装:

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

  • npm install mqtt --save
  • yarn add mqtt
  1. 通过 CDN 引入

    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
  2. 下载到本地,然后使用相对路径引入

    <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

连接关键代码:

<script>
import mqtt from 'mqtt'

export default {
  data() {
    return {
      connection: {
        host'broker.emqx.io',
        port8083,
        endpoint'/mqtt',
        cleantrue// 保留会话
        connectTimeout4000// 超时时间
        reconnectPeriod4000// 重连时间间隔
        // 认证信息
        clientId'mqttjs_3be2c321',
        username'emqx_test',
        password'emqx_test',
      },
      subscription: {
        topic'topic/mqttx',
        qos0,
      },
      publish: {
        topic'topic/browser',
        qos0,
        payload'{ "msg": "Hello, I am browser." }',
      },
      receiveNews'',
      qosList: [
        { label0value0 },
        { label1value1 },
        { label2value2 },
      ],
      client: {
        connectedfalse,
      },
      subscribeSuccessfalse,
    }
  },

  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 = {
        connectedfalse,
      }
      console.log('Successfully disconnected!')
    } catch (error) {
      console.log('Disconnect failed', error.toString())
    }
  }
}

上述内容就是 Vue项目中MQTT如何使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://my.oschina.net/u/4174826/blog/4641856

AI

开发者交流群×