<template>
<div class="page">
<el-button type="primary" @click="createConnection">连接MQTT</el-button>
<el-button type="primary" @click="doSubscribe">订阅主题</el-button>
<el-button type="primary" @click="doUnSubscribe">取消主题</el-button>
<el-button type="primary" @click="destroyConnection">断开MQTT</el-button>
</div>
</template>
<script>
import Stomp from 'stompjs';
export default {
data() {
return {
client: null,
frame: null,
options: {
vhost: '/',
incoming: 8000, // 心跳包时间,(须大于0,且小于10000,因为服务器可能默认10秒没心跳就会断开)
outgoing: 8000, // 心跳包时间,(须大于0,且小于10000,因为服务器可能默认10秒没心跳就会断开)
account: 'taijuyun',
pwd: '123456',
server: 'ws://114.216.4.244:15674/ws',
message: '',
},
};
},
methods: {
connect(options) {
this.options = { ...this.options, ...options };
const mqUrl = this.options.server;
const ws = new WebSocket(mqUrl);
ws.onclose = close => {
console.log('webSocket关闭', close);
};
ws.onerror = error => {
console.log('webSocket异常', error);
};
ws.onopen = success => {
console.log('webSocket连接成功', success);
};
this.client = Stomp.over(ws);
this.client.heartbeat.incoming = this.options.incoming;
this.client.heartbeat.outgoing = this.options.outgoing;
this.client.debug = null; //关闭控制台调试
//连接成功时
const onConnect = async () => {
console.log('stomp 连接成功!');
//订阅消息
//this.subscribe();
};
//发生错误自动重连
const onError = errorMsg => {
console.error(`stomp 断开连接,正在准备重新连接...`, errorMsg);
this.connect(this.options);
};
//开始连接
this.client.connect(
this.options.account, // 用户名
this.options.pwd, // 密码
onConnect,
onError,
this.options.vhost
);
},
doSubscribe() {
this.currentSubscribe = this.client.subscribe('/topic/5ccde2da94d141769c9c5b1ac49f73d7', function (messages) {
console.log('receive:', messages);
});
},
doUnSubscribe() {
this.currentSubscribe.unsubscribe();
},
createConnection() {
this.connect();
},
destroyConnection() {
this.client.disconnect(() => {
console.log('已关闭mq连接');
});
},
},
created() {},
mounted() {
this.connect();
},
};
</script>