vue连接mqtt

vue连接mqtt:

  1. 首先导入五个依赖:

    1. mqtt依赖:

      npm install mqtt
      
    2. webpack 依赖:

      npm install webpack
      
    3. buffer 依赖:

      npm install buffer
      
    4. process 依赖:

      npm install process
      
    5. url 依赖:

      npm install url
      
  2. 第二步:在 vue.config.js 文件中进行配置

    //首先导入 webpack
    const webpack =require("webpack")
    
    //进行配置
    configureWebpack: {
        plugins: [
              new webpack.ProvidePlugin({
                process: 'process/browser',
                Buffer: ['buffer', 'Buffer']
              })
        ]
      }
    
  3. 第三步:以下即是一个组件例子 可直接插入引用

    1. 更改位置:

       host: "broker.emqx.io",//链接地址
       port:"8083",//端口
       
       subscription: {
              topic: "suiji",//订阅主题
              qos: 0, //qos配置
            },
      
    2. 例程

      <template>
        <div>
          <h2>你好</h2>
          <h3>{{msg}}</h3>
          <button @click="show">点我发数据</button>
        </div>
      </template>
      
      <script>
      import mqtt from "mqtt";
      export default {
        name: "MqttTable",
        data() {
          return {
            connection: {
              host: "broker.emqx.io",//链接地址
              port:"8083",//端口
              endpoint: "/mqtt",
              clean: true, // 保留会话
              connectTimeout: 4000, // 超时时间
              reconnectPeriod: 4000, // 重连时间间隔
              // 认证信息
              clientId: "mqttjs_3be2c321" + new Date().getTime(),
              username: "",//用户名 不用的话什么也不用填
              password: "",//密码 不用的话什么也不用填
            },
            subscription: {
              topic: "suiji",
              qos: 0,
            },
            receiveNews: "",
            client: {
              connected: false,
            },
            subscribeSuccess: false,
            msg:null,
          };
        },
        created() {
        },
        mounted() {
          this.createConnection();
        },
        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}`;
            const {topic, qos} = this.subscription;
            try {
              this.client = mqtt.connect(connectUrl, options);
            } catch (error) {
              console.log("mqtt.connect error", error);
            }
            //连接mqtt
            this.client.on("connect", () => {
              console.log("Connection succeeded!");
              //订阅
              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);
              });
            });
            this.client.on("error", (error) => {
              console.log("Connection failed", error);
            });
            //获取消息
            this.client.on("message", (topic, message) => {
              console.log(message.toString())
              this.msg=message.toString()
            });
            //下发 两个参数,一个是定义的topic另一个是你需要下发的内容
            this.client.publish('topic', content)
          },
            //这里只是将上面的发布代码单独提到一个函数中进行调用
          show()
          {
              //下发 两个参数,一个是定义的topic另一个是你需要下发的内容
            this.client.publish('this.subscription.topic', "你好吗")
            console.log("我要发消息了")
          },
        },
      
        destroyed() {
        },
      }
      </script>
      
      <style scoped>
      
      </style>
      
  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值