赞
踩
mounted() {
this.initWebSocket();
},
websocket相关函数封装
initWebSocket() {
this.ws = new WebSocket('ws://...');
this.ws.onopen = () => {
console.log('push_ws:onopen');
};
this.ws.onclose = () => {
this.ws.onmessage = null;
this.ws = null;
console.log('push_ws:onclose');
};
this.ws.onerror = () => {
this.ws = null;
console.log('push_ws:onerror');
};
this.ws.onmessage = (e) => {
console.log(e)
}
}
<template>
<div></div>
</template>
<script>
import mqtt from 'mqtt';
import { defineComponent, reactive, onBeforeUnmount, onMounted, watch, unref } from 'vue';
export default defineComponent({
name: 'MqttConnect',
props: {
host: {
default: '',
type: String,
},
port: {
default: 28083,
type: Number,
},
subscription: {
default: [],
type: Array[String],
},
},
setup(prop, { emit }) {
onBeforeUnmount(() => {
destroyConnection();
});
onMounted(() => {
createConnection();
});
const data = reactive({
connection: {
host: '',
port: null,
endpoint: '/mqtt',
clean: true, // 保留会话
connectTimeout: 4000, // 超时时间
//reconnectPeriod: 4000, // 重连时间间隔
// 认证信息
clientId: 'mqttjs_3be2c321',
username: '',
password: '',
},
publish: {
topic: 'home/garden/fountain',
qos: 0,
payload: '{ "msg": "Hello, I am browser." }',
},
receiveNews: '',
qosList: [
{ label: 0, value: 0 },
{ label: 1, value: 1 },
{ label: 2, value: 2 },
],
client: {
connected: false,
},
subscribeSuccess: false,
});
// 创建连接
const createConnection = () => {
data.connection.host = prop.host;
data.connection.port = prop.port;
data.connection.clientId = 'mqttjs_3be2c321' + Math.random() * 100000;
const { host, port, endpoint, ...options } = data.connection;
let connectUrl;
if (window.location.href.indexOf('https') !== -1)
connectUrl = 'wss://www.hikailink-cloud.com/mqtt8083';
else connectUrl = `ws://${host}:${port}${endpoint}`;
data.client = mqtt.connect(connectUrl, options);
data.client.on('connect', () => {
console.log('Connection succeeded!');
});
data.client.on('error', (error) => {
console.log('Connection failed', error);
});
data.client.on('message', (topic, message) => {
if (message.toString()) {
emit('getMessage', topic, JSON.parse(message.toString()));
}
});
prop.subscription.forEach((item) => {
doSubscribe(item, 0);
});
};
// 订阅主题
const doSubscribe = (topic, qos) => {
data.client.subscribe(topic, { qos }, (error, res) => {
if (error) {
console.log('Subscribe to topics error', error);
return;
}
data.subscribeSuccess = true;
console.log('Subscribe to topics res', res);
});
};
// 取消订阅
const doUnSubscribe = (topic) => {
data.client.unsubscribe(topic, (error) => {
if (error) {
console.log('Unsubscribe error', error);
}
});
};
// 断开连接
const destroyConnection = () => {
if (data.client.connected) {
try {
data.client.end();
data.client = {
connected: false,
};
console.log('Successfully disconnected!');
} catch (error) {
console.log('Disconnect failed', error.toString());
}
}
};
watch(
() => unref(prop).subscription,
(subscription, old) => {
old.forEach((item) => {
doUnSubscribe(item);
});
setTimeout(() => {
subscription.forEach((item) => {
doSubscribe(item, 0);
});
}, 300);
}
);
},
});
</script>
<style scoped></style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。