MQTT协议

MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是IBM开发的一个即时通讯协议,有可能成为物联网的重要组成部分。该协议支持所有平台,几乎可以把所有联网物品和外部连接起来,被用来当做传感器和制动器(比如通过Twitter让房屋联网)的通信协议。

MQTT是轻量级基于代理的发布/订阅的消息传输协议,它可以通过很少的代码和带宽和远程设备连接。例如通过卫星和代理连接,通过拨号和医疗保健提供者连接,以及在一些自动化或小型设备上,而且由于小巧,省电,协议开销小和能高效的向一和多个接收者传递信息,故同样适用于称动应用设备上。

vue利用mqtt服务端实现即时通讯

在大部分项目中,前后端交互只是前端请求后端的接口,拿到数据后再处理,前段时间我手上的一个项目需要用到mqtt,使用后觉得真神奇,只需要订阅就能实时获取到数据,废话不多说,妹妹给你们上步骤!

1.在vue项目中安装mqtt.js

npm install mqtt --save

2.在项目的main.js或者在需要用到的vue页面上引用

import mqtt from 'mqtt'

3.在vue页面的data中定义一个client对象,方便后面使用

client: {}

ok,接下来就是重点了,首先我们得连接mqtt,连接mqtt的方法有个回调函数,我接下来就把订阅的方法写在连接成功后的回调里,这样能保证不出错,上代码!

4.连接mqtt并订阅

  //连接服务器
    connect() {
      let options = {
        username: "xxx",
        password: "xxxx",
        cleanSession : false,
        keepAlive:60,
        clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
        connectTimeout: 4000
      }
      this.client = mqtt.connect('ws://192.168.xxx.xx:8083/mqtt',options);
      this.client.on("connect", (e)=>{
        console.log("成功连接服务器:",e);
        //订阅三个名叫'top/#', 'three/#'和'#'的主题
        this.client.subscribe(['top/#', 'three/#', '#'], { qos: 1 }, (err)=> {
          if (!err) {
            console.log("订阅成功");
            //向主题叫“pubtop”发布一则内容为'hello,this is a nice day!'的消息
            this.publish("pubtop", 'hello,this is a nice day!')
          } else {
            console.log('消息订阅失败!')
          }
        });
      });
      //重新连接
      this.reconnect()
      //是否已经断开连接
      this.mqttError()
      //监听获取信息
      this.getMessage()
    }

5.发布消息方法

    //发布消息@topic主题  @message发布内容
    publish(topic,message) {
      if (!this.client.connected) {
        console.log('客户端未连接')
        return
      }
      this.client.publish(topic,message,{qos: 1},(err) => {
        if(!err) {
          console.log('主题为'+topic+ "发布成功")
        }
      })
    }

6.监听并接收上面订阅的三个主题的信息

    //监听接收消息
    getMessage() {
      this.client.on("message", (topic, message) => {
        if(message) {
          console.log('收到来着',topic,'的信息',message.toString())
          const res = JSON.parse(message.toString())
          //console.log(res, 'res')
          switch(topic) {
             case 'top/#' :
               this.msg = res
               break;
             case 'three/#' :
               this.msg = res
               break;
             case 'three/#' :
               this.msg = res
               break;
             default:
               return
               this.msg = res
           }
           this.msg = message
        }
      });
    },

7.监听服务器是否连接失败

    //监听服务器是否连接失败
    mqttError() {
      this.client.on('error',(error) => {
        console.log('连接失败:',error)
        this.client.end()
      })
    },

8.取消订阅

    //取消订阅
    unsubscribe() {
      this.client.unsubscribe(this.mtopic, (error)=> {
        console.log('主题为'+ this.mtopic+'取消订阅成功',error)
      })
    },

9.断开连接

    //断开连接
    unconnect() {
      this.client.end()
      this.client = null
      console.log('服务器已断开连接!')
    },

10.监听服务器重新连接

    //监听服务器重新连接
    reconnect() {
      this.client.on('reconnect', (error) => {
          console.log('正在重连:', error)
      });
    },

总结

到此这篇关于vue中利用mqtt服务端实现即时通讯的文章就介绍到这了,更多相关vue用mqtt即时通讯内容请搜索悠悠之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠悠之家!

点赞(76)

评论列表共有 0 条评论

立即
投稿
返回
顶部