写一个webscoket.js文件
class WebSocketClass {
constructor(url = '', webSocketError = 0, callback = () => { }) {
this.instance = null;
this.callback = callback; // 回调函数
this.wsurl = url; // ws路径
this.webSocketError = webSocketError // 初始化重连次数
this.webSocketErrorMax = 10 // 最大的重连次数
this.socketInit(url);
}
static getInstance() {
if (!this.instance) {
this.instance = new WebSocketClass(this.wsurl, this.webSocketError, this.callback);
}
return this.instance;
}
// 初始化socke
socketInit(url) {
if (url != undefined) {
this.ws = new WebSocket(url);
this.ws.onopen = e => {
this.status = 'open';
console.log(`连接成功`, e);
this.getMessage();
};
this.ws.onclose = msg => {
console.log(msg, 'oncloseonclose');
// 重连
if (this.webSocketError < this.webSocketErrorMax) {
setTimeout(() => {
this.socketInit(this.wsurl)
}, 500)
} else {
console.log('组件销毁或者重连数次过多');
}
}
this.ws.onerror = err => {
this.webSocketError++
console.log(err, 'onerroronerror');
}
}
}
// 接受消息
getMessage() {
this.ws.onmessage = e => {
this.callback(e.data)
}
}
// 手动关闭socket
close() {
this.status = 'close';
this.ws.send('close');
this.webSocketError = 89
this.ws.close();
}
}
export default WebSocketClass;
使用封装的websocket
<script>
import WebSocketClass from "@/common/websocket";
export default {
props: {},
data() {
return {
homeWs: null,
};
},
computed: {
},
created() {
},
mounted() {
this.init();
},
watch: {
},
methods: {
init() {
this.homeWs = new WebSocketClass("ws://xxxxxxxxx", 0, msg => {
console.log(msg)
});
}
},
components: {},
destroyed() {
this.homeWs.close();
}
};
</script>