websocket 具体内容参考了 原文
import {
ref, onUnmounted} from 'vue';
import dayjs from "dayjs";
class Socket {
url;
ws = null;
opts;
reconnectAttempts = 0;
listeners = {
};
heartbeatInterval = null;
constructor(url, opts = {
}) {
this.url = url;
this.opts = {
// 心跳检测
heartbeatInterval: 30000,
// 重新连接时间间隔
reconnectInterval: 5000,
// 重连的次数
maxReconnectAttempts: 3,
...opts
};
this.init();
}
init() {
this.ws = new WebSocket(this.url);
this.ws.onopen = this.onOpen.bind(this);
this.ws.onmessage = this.onMessage.bind(this);
this.ws.onerror = this.onError.bind(this);
this.ws.onclose = this.onClose.bind(this);
}
onOpen(event) {
if (event) {
console.log(`%c websocket 已建立连接 ${
dayjs(new Date()).format("HH:mm:ss")}`, 'color: green');
this.reconnectAttempts = 0;
this.startHeartbeat();
this.emit('open', event);
}
}
onMessage(event) {
this.emit('message', event.data