vue中使用MQTT

MQTT 发布订阅模式简述网址:https://www.cnblogs.com/emqx/p/11799138.html

MQTT Broker 的连接使用 EMQ 提供的线上版 Websocket 工具:http://tools.emqx.io

操作步骤

1、填写基础信息

2、编辑基本信息,同时对照信息创建连接

3、发送消息时订阅通配符主题

4、完整代码

    安装mqtt库

    npm install mqtt --save


<template>

  <div id="app">

    <p>mqtt收到的数据:</p>

    <p>{{this.msg}}</p>

    <a-button @click="doPublish">发布</a-button>

  </div>

</template>

<script>

import mqtt from 'mqtt'

export default {

  data() {

    return {

      msg: '--',

      connection:{

        host: 'broker.emqx.io',

        port: 8083,

        endpoint: 'mqtt',

      },

      options:{

        connectTimeout: 40000,

        clientId: 'mqttx_6c65c4df',//认证消息

        username: '',

        password: '',

        clean: true

      },

      client: {

        connected: false,

      },

      publish: {

        topic: 'testtopic/cc',

        qos: 0

      },

    }

  },

  created() {

    this.createConnection()

  },

  methods: {

    // 创建连接

    createConnection(){

      this.client = mqtt.connect(`ws://${this.connection.host}:${this.connection.port}/${this.connection.endpoint}`, this.options)

      this.client.on('connect', () => {

        console.log("连接成功!!!")

        this.client.subscribe(this.publish.topic, { qos: this.publish.qos }, (error) => {

          if (!error) {

            console.log('订阅成功')

          } else {

            console.log('订阅失败')

          }

        })

      })

      // 接收消息处理

      this.client.on('message', (topic, message) => {

        console.log('收到来自', topic, '的消息', message.toString())

        this.msg = message.toString()

      })

    },

    // 发布消息

    doPublish() {

      this.client.publish(this.publish.topic, this.publish.qos,this.msg);

    }

  }

}

</script>

<style scoped>

</style>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容