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

npm install mqtt@3.0.0

注意要指定下载3.0.0版本

// 引入MQTT
const mqtt = require('mqtt/dist/mqtt.js')
// 声明client
data(){
	return {
		client: null
	}
}
//方法
//连接服务器
    connect() {
      let options = {
        username: "xxx",
        password: "xxxx",
        cleanSession : false,
        keepAlive:60,
        clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
        connectTimeout: 4000
      }
      //如果是apk,ws换成wx
      this.client = mqtt.connect('ws://ip:port/mqtt',options);
      this.client.on("connect", (e)=>{
        console.log("成功连接服务器:",e);
        // 订阅 topic。如果订阅多个["test1","test2"]
        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()
    }
    
    //发布消息@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+ "发布成功")
        }
      })
    }
//监听接收消息
    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
        }
      });
    }
//监听服务器是否连接失败
    mqttError() {
      this.client.on('error',(error) => {
        console.log('连接失败:',error)
        this.client.end()
      })
    }
//取消订阅
    unsubscribe() {
      this.client.unsubscribe(this.mtopic, (error)=> {
        console.log('主题为'+ this.mtopic+'取消订阅成功',error)
      })
    }
    
//断开连接
    unconnect() {
      this.client.end()
      this.client = null
      console.log('服务器已断开连接!')
    },
//监听服务器重新连接
    reconnect() {
      this.client.on('reconnect', (error) => {
          console.log('正在重连:', error)
      });
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值