最佳websocket封装

封装了weboskect,完美支持了断网重连、自动心跳的功能,且完全兼容原生写法,无任何学习负担,开开箱即用!

import { EventDispatcher } from './dispatcher';

export class WebSocketClient extends EventDispatcher {
    // #socket链接
    url = '';
    // #socket实例
    socket = null;
    // #重连次数
    reconnectAttempts = 0;
    // #最大重连数
    maxReconnectAttempts = 5;
    // #重连间隔
    reconnectInterval = 10000; // 10 seconds
    // #发送心跳数据间隔
    heartbeatInterval = 1000 * 30;
    // #计时器id
    heartbeatTimer = undefined;
    // #彻底终止ws
    stopWs = false;
    // *构造函数
    constructor(url) {
        super();
        this.url = url;
    }
    // >生命周期钩子
    onopen(callBack) {
        this.addEventListener('open', callBack);
    }
    onmessage(callBack) {
        this.addEventListener('message', callBack);
    }
    onclose(callBack) {
        this.addEventListener('close', callBack);
    }
    onerror(callBack) {
        this.addEventListener('error', callBack);
    }
    // >消息发送
    send(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(message);
        } else {
            console.error('[WebSocket] 未连接');
        }
    }

    // !初始化连接
    connect() {
        if (this.reconnectAttempts === 0) {
            this.log('WebSocket', `初始化连接中...          ${this.url}`);
        }
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            return;
        }
        this.socket = new WebSocket(this.url);

        // !websocket连接成功
        this.socket.onopen = event => {
            this.stopWs = false;
            // 重置重连尝试成功连接
            this.reconnectAttempts = 0;
            // 在连接成功时停止当前的心跳检测并重新启动
            this.startHeartbeat();
            this.log('WebSocket', `连接成功,等待服务端数据推送[onopen]...     ${this.url}`);
            this.dispatchEvent('open', event);
        };

        this.socket.onmessage = event => {
            this.dispatchEvent('message', event);
            this.startHeartbeat();
        };

        this.socket.onclose = event => {
            if (this.reconnectAttempts === 0) {
                this.log('WebSocket', `连接断开[onclose]...    ${this.url}`);
            }
            if (!this.stopWs) {
                this.handleReconnect();
            }
            this.dispatchEvent('close', event);
        };

        this.socket.onerror = event => {
            if (this.reconnectAttempts === 0) {
                this.log('WebSocket', `连接异常[onerror]...    ${this.url}`);
            }
            this.closeHeartbeat();
            this.dispatchEvent('error', event);
        };
    }

    // > 断网重连逻辑
    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            this.log('WebSocket', `尝试重连... (${this.reconnectAttempts}/${this.maxReconnectAttempts})       ${this.url}`);
            setTimeout(() => {
                this.connect();
            }, this.reconnectInterval);
        } else {
            this.closeHeartbeat();
            this.log('WebSocket', `最大重连失败,终止重连: ${this.url}`);
        }
    }

    // >关闭连接
    close() {
        if (this.socket) {
            this.stopWs = true;
            this.socket.close();
            this.socket = null;
            this.removeEventListener('open');
            this.removeEventListener('message');
            this.removeEventListener('close');
            this.removeEventListener('error');
        }
        this.closeHeartbeat();
    }

    // >开始心跳检测 -> 定时发送心跳消息
    startHeartbeat() {
        if (this.stopWs) return;
        if (this.heartbeatTimer) {
            this.closeHeartbeat();
        }
        this.heartbeatTimer = setInterval(() => {
            if (this.socket) {
                this.socket.send(JSON.stringify({ type: 'heartBeat', data: {} }));
                this.log('WebSocket', '送心跳数据...');
            } else {
                console.error('[WebSocket] 未连接');
            }
        }, this.heartbeatInterval);
    }

    // >关闭心跳
    closeHeartbeat() {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = undefined;
    }
}
class Log {
    static console = true;
    log(title, text) {
        if (!Log.console) return;
        if (import.meta.env.MODE === 'production') return;
        const color = '#ff4d4f';
        console.log(
            `%c ${title} %c ${text} %c`,
            `background:${color};border:1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`,
            `border:1px solid ${color}; padding: 1px; border-radius: 0 2px 2px 0; color: ${color};`,
            'background:transparent'
        );
    }
    closeConsole() {
        Log.console = false;
    }
}
export class EventDispatcher extends Log {
    listeners = {};

    addEventListener(type, listener) {
        if (!this.listeners[type]) {
            this.listeners[type] = [];
        }
        if (this.listeners[type].indexOf(listener) === -1) {
            this.listeners[type].push(listener);
        }
    }

    removeEventListener(type) {
        this.listeners[type] = [];
    }

    dispatchEvent(type, data) {
        const listenerArray = this.listeners[type] || [];
        if (listenerArray.length === 0) return;
        listenerArray.forEach(listener => {
            listener.call(this, data);
        });
    }
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WebSocket通信的工具是一种在Web应用程序中实现实时双向通信的技术。它能够提供长连接,并允许服务器主动向客户端推送数据,而无需客户端发起请求。以下是几种常用的WebSocket通信工具: 1. Socket.io:Socket.io是一种基于Node.js的实时通信库,提供了跨平台的双向通信。它支持WebSocket并且兼容旧版浏览器,还可以自动选择最佳通信方式(WebSocket、flash或HTTP轮询)以确保最佳性能。Socket.io还提供了丰富的事件和API,使得实时通信的开发变得简单和可靠。 2. SignalR:SignalR是微软开发的实时通信框架,允许服务器端和客户端之间进行实时双向通信。它支持WebSocket以及其他传输方式(如Server-Sent Events和Long Polling),并且可以在多种平台上进行开发,包括ASP.NET、ASP.NET Core和JavaScript。 3. SockJS:SockJS是一种JavaScript库,它提供了WebSocket封装,可以在不支持WebSocket的浏览器中使用其他传输方式(如AJAX轮询)来实现实时通信。SockJS具有跨浏览器兼容性,并且可以与WebSocket搭配使用以提供更好的性能和效果。 4. WebSockets.org:WebSockets.org是一个开源的WebSocket库和资源集合,提供了各种不同语言和平台的WebSocket实现。它包括了代码示例、文档、教程等内容,可以帮助开发者更轻松地使用WebSocket进行通信。 这些工具都提供了一种简单且高效的方式来实现WebSocket通信,使得开发者能够快速构建实时的Web应用程序。通过利用WebSocket的长连接特性,可以实现即时的数据更新、聊天功能、实时协作等多种实时应用场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值