类组件化websocket的方法(心跳机制)

发布于:2024-09-17 ⋅ 阅读:(60) ⋅ 点赞:(0)
/**
 * WebSocket统一管理
 */
export class WebSocketClient {
    constructor(url) {
        if (!url) {
            throw new Error("WebSocket URL is required.");
        }
        this.url = url;
        this.websocket = null;
        this.listeners = {};
        this.heartbeatInterval = 30000; // 心跳检测间隔(毫秒)
        this.reconnectDelay = 10000; // 断线后重连间隔(毫秒)
        this.pingTimeout = null;
        this.reconnectTimeout = null;
        this.isManuallyClosed = false;
    }

    /** 初始化 WebSocket 连接 */

    connect() {
        this.websocket = new WebSocket(this.url);

        this.websocket.onopen = () => {
            // console.log("WebSocket connection opened.");
            // this.startHeartbeat(); // 开始心跳检测
            this.dispatch("open");
        };

        this.websocket.onmessage = (event) => {
            const data = JSON.parse(event.data ?? "{}");
            this.dispatch("message", data);
        };

        this.websocket.onclose = () => {
            // console.log("WebSocket connection closed.");
            this.dispatch("close");
            // this.stopHeartbeat(); // 停止心跳检测
            if (!this.isManuallyClosed) {
                this.reconnect(); // 自动重连
            }
        };

        this.websocket.onerror = (error) => {
            console.error("WebSocket error:", error);
            this.dispatch("error", error);
        };
    }

    // 关闭 WebSocket 连接
    close() {
        this.isManuallyClosed = true; // 手动关闭连接时,不进行重连
        if (this.websocket) {
            this.websocket.close();
        }
    }

    /**
     * 添加事件监听函数
     * @param { 'open' | 'message' | 'close' | 'error' } eventType
     * @param { (data) => void } callback
     */
    addListener(eventType, callback) {
        if (!this.listeners[eventType]) {
            this.listeners[eventType] = [];
        }
        this.listeners[eventType].push(callback);
    }

    /** 移除事件监听函数 */
    removeListener(eventType, callback) {
        if (!this.listeners[eventType]) return;

        this.listeners[eventType] = this.listeners[eventType].filter(
            (listener) => listener !== callback
        );
    }

    /** 派发事件 */
    dispatch(eventType, data) {
        if (!this.listeners[eventType]) return;

        this.listeners[eventType].forEach((listener) => listener(data));
    }

    // 心跳检测 (ping/pong)
    startHeartbeat() {
        if (this.pingTimeout) {
            clearTimeout(this.pingTimeout);
        }

        // 定时发送心跳
        this.pingTimeout = setTimeout(() => {
            if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
                this.websocket.send("ping"); // 发送心跳包
                console.log("Ping sent to server.");
            }

            // 继续心跳
            this.startHeartbeat();
        }, this.heartbeatInterval);
    }

    // 停止心跳检测
    stopHeartbeat() {
        if (this.pingTimeout) {
            clearTimeout(this.pingTimeout);
        }
    }

    // 自动重连
    reconnect() {
        console.log(`正在重连${this.url} ${this.reconnectDelay / 1000} 秒...`);
        this.reconnectTimeout = setTimeout(() => {
            this.connect();
        }, this.reconnectDelay);
    }

    send(data) {
        this.websocket.send(data);
    }
}