index.html中引入mqtt文件 <script src="./js/mqttws31.min.js" type="text/javascript"></script>
vue 文件中使用
data(){
return{
topic:"message-topic",
color:""
}
}
mounted(){
this.MQTTconnect();
},
methods:{
//實時通信
MQTTconnect() {
const host = '192.168.x.xx';
const port = xxxx;
this.mqtt = new Paho.MQTT.Client( //實例化一個對象
host,
port,
"client" + this.getuuid(), //防止多個瀏覽器打開,導致的問題,保證唯一性
);
var options = {
timeout: 10,
useSSL: false,
cleanSession: false,
//如果為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;
//用戶名和密碼的驗證,我這里都為空;不加驗證
const username = "admin"
if (username != null) {
options.userName = 'admin';
options.password = '123';
}
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("onConnected");
//連接成功,發送信息,信息內容為12354654788
// this.mqtt.send(this.send_topic, "12354654788", 0);
//連接成功,訂閱信息
this.mqtt.subscribe(this.topic);
},
//連接丟失
onConnectionLost(response) {
console.log("異常掉線,掉線信息為:" + response.errorMessage);
},
//接收到消息,處理
onMessageArrived(message) {
console.log(message)
var topics = message.destinationName;
var msg = message.payloadString;
// console.log(msg)
//判斷主題,調用方法,這里可以訂閱多個主題,在此處判斷,接受不同的主題,調用不同的方法!
if (topics == this.topic) {
//添加
this.color = msg
}else {
return;
}
},
}