前端 webSocket 封装(开箱即用)

import { ElMessage } from "element-plus";
import { ref } from "vue";
import { websocketURL } from "@/utils/baseConfigs"

export default () => {
    // websocket.value 连接
    const websocket = ref()
    const timer = ref(null)
    const websocketId = ref(null)

    const messageData = ref("")
    const statusFlag = ref(false)
    const getConnection = (val) => {

        websocketId.value = val;
        if(websocketId.value){
            try {
                websocket.value = new WebSocket(
                    `${ websocketURL + "/record/websocket/" + websocketId.value}`
                );
                initwebsocket();
            } catch (error) {
                // console.log("error", error);
            }
        }
    }

    // 初始化socket方法
    const initwebsocket = () => {
        //连接错误
        websocket.value.onerror = setErrorMessage;

        // //连接成功
        websocket.value.onopen = setOnopenMessage;

        //收到消息的回调
        websocket.value.onmessage = setOnmessageMessage;

        //连接关闭的回调
        websocket.value.onclose = setOncloseMessage;

        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket.value连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = onbeforeunload;
    }
    const setErrorMessage = () => {
        // 连接错误
    }
    const setOnopenMessage = () => {
        // 自定义心跳通信数据
        let obj = {
            userId: websocketId.value
        }
        timer.value = setInterval(() => {
            sendwebsocket(JSON.stringify(obj))
        }, 5 * 1000)
    }
    // 接收后端发的消息
    const setOnmessageMessage = (event) => {
        
        if(event.data === "heartbeat"){
            // 心跳检测
        }else{
            messageData.value = event.data
        }
    }
    const setOncloseMessage = () => {
        // 连接关闭
    }
    const onbeforeunload = () => {
        // 卸载websocket
        closewebsocket();
        statusFlag.value = false;
    }
    //websocket.value发送消息
    const sendwebsocket = (text) => {
        websocket.value.send(text);
    }
    const closewebsocket = () => {
        // 销毁定时任务
        // 销毁websocket心跳检测
        if (timer.value !== null) {
            clearInterval(timer.value);
            timer.value = null;
        }
    }

    return{
        messageData,getConnection,onbeforeunload,statusFlag
    }
}

其他hooks或者组件调用方式

import websocketHooks from "@/hooks/websocketHooks";

const { messageData,getConnection,onbeforeunload } = websocketHooks();

// 创建时候自动连接
onMounted(()=>{
    let timestamp = Date.now();
    // 将时间戳转换为字符串
    let timestampString = timestamp.toString();
    let websocketId = JSON.stringify(userId.value) + timestampString;
    getConnection(websocketId)
})

// 销毁
onBeforeUnmount(()=>{
   onbeforeunload()
})

### 前端 WebSocket 封装方法及示例 为了实现更稳定可靠的 WebSocket 连接管理,通常会将 WebSocket 功能封装到一个独立的类或模块中。这不仅有助于简化代码逻辑,还能增强错误处理能力和自动重连机制。 #### 创建可重连的 WebSocket 类 通过定义一个 `WebSocket` 类来封装基本功能,并加入自动重连特性: ```javascript class ReconnectingWebSocket { constructor(url, protocols = [], options = {}) { this.url = url; this.protocols = protocols; this.options = options; this.reconnectInterval = options.reconnectInterval || 1000; // 默认重连间隔时间设为1秒 this.maxReconnectAttempts = options.maxReconnectAttempts || Infinity; // 设置最大尝试次数 this._ws = null; this._reconnectCount = 0; this.connect(); } connect() { try { console.log(`Connecting to ${this.url}`); this._ws = new WebSocket(this.url, this.protocols); this._ws.onopen = () => { console.log('Connected'); this._resetReconnectCounter(); }; this._ws.onerror = (error) => { console.error('Error:', error); }; this._ws.onclose = () => { console.warn('Connection closed. Attempting reconnect...'); setTimeout(() => this.reconnect(), this.reconnectInterval); }; this._ws.onmessage = (event) => { const message = JSON.parse(event.data); this.emit('message', message); }; } catch (e) { console.error(e.message); setTimeout(() => this.reconnect(), this.reconnectInterval); } } _resetReconnectCounter() { this._reconnectCount = 0; } reconnect() { if (++this._reconnectCount >= this.maxReconnectAttempts) { console.error('Max reconnection attempts reached.'); return; } this.connect(); } send(data) { if (!this.isConnected()) throw new Error('Not connected'); this._ws.send(JSON.stringify(data)); } close(code, reason) { if (this._ws && this._ws.readyState === WebSocket.OPEN) { this._ws.close(code, reason); } } isConnected() { return this._ws?.readyState === WebSocket.OPEN; } emit(eventName, data) { window.dispatchEvent(new CustomEvent(eventName, { detail: data })); } } ``` 此段代码实现了带有自动重试机制的 WebSocket 客户端[^3]。每当连接断开时,客户端会在指定的时间间隔后再次尝试建立新的连接直到达到预设的最大重试次数为止。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值