vue连接MQTT即时通讯

创建组件Mqttws

在index.js

data () {
    return {
       reconnectTimeout: 2000,
        mqtt: {},
        msg:"",
};
mounted(){
    this.MQTTconnect();
},

  methods: {
      addtopic(msg) {
        this.msg = msg;
      },
       //实时通信
       sendMQTTMsg(topic,message){
           this.mqtt.send(topic,message);
           console.log("发送消息成功", message)
       },
            MQTTconnect() {
                this.mqtt = new Paho.MQTT.Client(  //实例化一个对象
                    host,
                    port,
                    "client" + this.getuuid(),  //防止多个浏览器打开,导致的问题,保证唯一性
                );
                var options = { 
                    timeout: 10,
                    useSSL: useTLS,
                    cleanSession: cleansession,
                   //如果为false(flag=0),Client断开连接后,Server应该保存Client的订阅信息。如果为true(flag=1),表示Server应该立刻丢弃任何会话状态信息。
                    onSuccess: this.onConnect,
                    onFailure: function(message) {
                        //连接失败定时重连
                        setTimeout(this.MQTTconnect, this.reconnectTimeout);
                    }
                };
                this.mqtt.onConnectionLost = this.onConnectionLost;
                this.mqtt.onMessageArrived = this.onMessageArrived;
                //用户名和密码的验证,我这里都为空;不加验证
                if (username != null) {
                    options.userName = username;
                    options.password = password;
                }
                this.mqtt.connect(options);
            },
            //uuid随机生成
            getuuid() {
                var uid = [];
                var hexDigits = "0123456789abcdefghijklmnopqrst";
                for (var i = 0; i < 32; i++) {
                    uid[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                uid[6] = "4";
                uid[15] = hexDigits.substr((uid[15] & 0x3) | 0x8, 1);
                var uuid = uid.join("");
                return uuid;
            },
            //连接
            onConnect() {
                console.log('连接成功')
                //连接成功,订阅主题
                var _this=this;
            // _this.mqtt.subscribe(主题,{qos:2})
            _this.mqtt.subscribe("/maintain/room/master/client/", {
            	 qos: 2  
            //   QoS0,最多一次送达。也就是发出去就fire掉,没有后面的事情了。
            //   QoS1,至少一次送达。发出去之后必须等待ack,没有ack,就要找时机重发
            //   QoS2,准确一次送达。消息id将拥有一个简单的生命周期。

			});

            //连接丢失
            onConnectionLost(response) {
                console.log("异常掉线,掉线信息为:" + response.errorMessage);
            },
    
            //接收到消息,处理
            onMessageArrived(message) {
                console.log(message)
                // var topics = message.destinationName;
                // var msg = message.payloadString;
                // //判断主题,调用方法,这里可以订阅多个主题,在此处判断,接受不同的主题,调用不同的方法!
                if(message.destinationName === "/maintain/room/master/client/"){
                    if(JSON.parse(message.payloadString).action =="_updatestatus"){
                     this.$emit('sendModel',message.payloadString );
                    }
                
            },
            // 断开mqtt连接
            disconnect () {
            	this.mqtt.disconnect()
            }
  }
}

获取订阅信息页面

<template>
	<div>
		<Mqtt ref="mqtt" @sendModel="sendModel"></Mqtt>
	</div>
</template>
<script>
	import Mqtt from '@/components/Mqttws';
	export default {
		components: {
			Mqtt
		}
	}
	methods: {
		//获取mqtt订阅信息
		sendModel(msg){
			var data = JSON.parse(msg)
			console.log('订阅信息---',data)
		}
	}
</script>

发布订阅

<template>
	<div>
		<button @click="sendClick">发布</button>
		<Mqtt ref="mqtt"></Mqtt>
	</div>
</template>
<script>
	import Mqtt from '@/components/Mqttws';
	export default {
		components: {
			Mqtt
		}
	}
	methods: {
		//发布主题信息
		sendClick(){
			this.$refs.mqtt.sendMQTTMsg("主题",JSON.stringify(message))
		}
	}
</script>

绑定服务器地址

在static创建config.js

host = 'IP'; // hostname or IP address ,自己配的消息队列服务,这里用的在线的服务,
port = 9001;  //端口
addtopic = 'topic01'; //约定的主题
//下面暂时不用在意,下次会讲
useTLS = false;
username = null;
password = null;
cleansession = false;

网上下载一个mqttws31.js包

在index.html引入mqttws31.js和config.js

<title>XX系统</title>
    <script src="./static/mqttws31.js" type="text/javascript"></script>
    <script src="./static/config.js" type="text/javascript"></script>

你可能感兴趣的:(vue,vue.js)