WebSocket 封裝

/**
 * 使用方法
 * import WebSocket from '@/utils/websocket';
 * const options = {
 *  url: 'ws://127.0.0.1:8080',
 *  onmessage: (res) => {
 *      // 接收數(shù)據(jù)后回調(diào)
 *  },
 *  // ?;钪芷?10s
 *  timer: 10000,
 *  // 斷線重連
 *  reconnect: true,
 * };
 * const socket = new WebSocket(options);
 * 
 * 手動(dòng)關(guān)閉
 * socket.close();
 */


class Socket {
    /**
     * 構(gòu)造函數(shù)
     * @param {object} params 構(gòu)造函數(shù)參數(shù)
     */
    constructor(params) {
        window.WebSocket = window.WebSocket || window.MozWebSocket;
        if (!window.WebSocket) { // 檢測(cè)瀏覽器支持
            console.error('錯(cuò)誤: 瀏覽器不支持websocket');
            return;
        }
        this.websocket = null;
        this.params = params;
        this.socketInit(params);
    }

    /**
     * 初始化socket
     * @param {string}   url     WebSocket服務(wù)器將響應(yīng)的URL
     * @param {function} onopen  open事件的回調(diào)函數(shù)
     * @param {function} onclose close事件的回調(diào)函數(shù)
     * @param {function} onerror error事件的回調(diào)函數(shù)
     * @param {function} onclose close事件的回調(diào)函數(shù)
     * @param {boolean}  reconnect 是否啟用斷線重連 默認(rèn)為false
     * @param {number}   timer   心跳周期 若為空或0則不啟用
     */
    socketInit({
        url,
        onopen,
        onmessage,
        onerror,
        onclose,
        reconnect = false,
        timer,
    }) {
        if (url !== undefined) {
            // 若不以wss?開(kāi)頭
            if (!/^wss?:\/\//.test(url)) {
                const {
                    protocol
                } = window.location;
                // 則自動(dòng)補(bǔ)上協(xié)議頭
                url = protocol === 'http:' ? 'ws://' + url : 'wss://' + url;
            }
            try {
                this.websocket = new WebSocket(url);
                // 用于指定連接成功后的回調(diào)函數(shù)。
                this.websocket.onopen = (e) => {
                    if (timer > 0) {
                        this.heartCheck(timer);
                    }
                    if (typeof onopen === 'function') {
                        onopen(e);
                    }
                };
                // 用于指定當(dāng)從服務(wù)器接受到信息時(shí)的回調(diào)函數(shù)。
                this.websocket.onmessage = (e) => {
                    onmessage(e);
                };
                // 用于指定連接關(guān)閉后的回調(diào)函數(shù)。
                this.websocket.onclose = (e) => {
                    reconnect && this.reconnect();
                    if (typeof onclose === 'function') {
                        onclose(e);
                    }
                };
                // 用于指定連接失敗后的回調(diào)函數(shù)。
                this.websocket.onerror = (e) => {
                    console.log('連接異常', e);
                    reconnect && this.reconnect();
                    if (typeof onerror === 'function') {
                        onerror(e);
                    }
                };
            } catch (e) {
                reconnect && this.reconnect();
            }
        }
    }

    // 發(fā)送消息
    send(message) {
        // readyState 1 表示已經(jīng)鏈接并且可以通訊
        if (!this.websocket || this.websocket.readyState !== 1) {
            console.log('請(qǐng)確認(rèn)websocket是否已經(jīng)鏈接并且可以通訊');
            return;
        }
        this.websocket.send(JSON.stringify(message));
    }

    // 手動(dòng)關(guān)閉socket
    close() {
        this.heartInterval && clearInterval(this.heartInterval);
        this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
        if (!this.websocket) {
            console.log('websocket 不可用');
            return;
        }
        this.websocket.close();
    }

    // 周期性發(fā)送ping 保活
    heartCheck(timer) {
        this.heartInterval = window.setInterval(() => {
            this.send({
                type: 'ping'
            });
        }, timer);
    }

    // 斷線重連
    reconnect() {
        if (this.lockReconnect) return;
        this.lockReconnect = true;
        this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
        this.reconnectTimeout = window.setTimeout(() => {
            this.socketInit(this.params);
            this.lockReconnect = false;
        }, 5000);
    }
}
export default Socket;
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.新建webSocket.js class webSocketClass { constructor(url,...
    Morbid_D閱讀 2,576評(píng)論 0 0
  • 一個(gè)通用的websocket封裝實(shí)例,包括Api的回調(diào),消息發(fā)送,連接關(guān)閉。連接出錯(cuò)重連,重連次數(shù)限制,重連超時(shí)停...
    一塊七毛五呢閱讀 3,146評(píng)論 0 5
  • 場(chǎng)景1: 只有單個(gè)長(zhǎng)鏈接,不要求?;?調(diào)用方法: 關(guān)閉方法: 場(chǎng)景2: 多個(gè)長(zhǎng)鏈接共存 如果還是需要單例調(diào)用的話,...
    moonCoder閱讀 11,699評(píng)論 7 4
  • 對(duì)原生websocket的使用封裝: 支持發(fā)生錯(cuò)誤后的自動(dòng)重連 支持on與emit方法 暴露open,close,...
    shuaiutopia閱讀 1,219評(píng)論 0 2
  • 1,封裝 websocket,創(chuàng)建websocket.js ,websocket 代碼如下 2,首先在使用 web...
    Henry01閱讀 1,565評(píng)論 0 1

友情鏈接更多精彩內(nèi)容