vue3 webSocket 封装及使用

vue3 webSocket 封装及使用

封装

import { ref, onUnmounted } from 'vue';
interface SocketOptions {
    heartbeatInterval?: number;
    reconnectInterval?: number;
    maxReconnectAttempts?: number;
}

class Socket {
    url: string;
    ws: WebSocket | null = null;
    opts: SocketOptions;
    reconnectAttempts: number = 0;
    listeners: { [key: string]: Function[] } = {};
    heartbeatInterval: number | null = null;

    constructor(url: string, opts: SocketOptions = {}) {
        this.url = url;
        this.opts = {
            heartbeatInterval: 30000, //心跳
            reconnectInterval: 5000, // 重连时间
            maxReconnectAttempts: 5, //重新连接次数
            ...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: Event) {
        console.log('WebSocket opened:', event);
        this.reconnectAttempts = 0;
        this.startHeartbeat();
        this.emit('open', event);
    }

    onMessage(event: MessageEvent) {
        console.log('WebSocket message received:', event.data);
        this.emit('message', event.data);
    }

    onError(event: Event) {
        console.error('WebSocket error:', event);
        this.emit('error', event);
    }

    onClose(event: CloseEvent) {
        console.log('WebSocket closed:', event);
        this.stopHeartbeat();
        this.emit('close', event);

        if (this.reconnectAttempts < this.opts.maxReconnectAttempts!) {
            setTimeout(() => {
                this.reconnectAttempts++;
                this.init();
            }, this.opts.reconnectInterval);
        }
    }

    startHeartbeat() {
        if (!this.opts.heartbeatInterval) return;

        this.heartbeatInterval = window.setInterval(() => {
            if (this.ws?.readyState === WebSocket.OPEN) {
                this.ws.send('ping');
            }
        }, this.opts.heartbeatInterval);
    }

    stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }

    send(data: string) {
        console.error('给socket发送消息============>',data)
        if (this.ws?.readyState === WebSocket.OPEN) {
            this.ws.send(data);
        } else {
            console.error('WebSocket is not open. Cannot send:', data);
        }
    }

    on(event: string, callback: Function) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
    }

    off(event: string) {
        if (this.listeners[event]) {
            delete this.listeners[event];
        }
    }

    emit(event: string, data: any) {
        this.listeners[event]?.forEach(callback => callback(data));
    }
}

export function useSocket(url: string, opts?: SocketOptions) {
    const socket = new Socket(url, opts);

    onUnmounted(() => {
        socket.off('open');
        socket.off('message');
        socket.off('error');
        socket.off('close');
    });

    return {
        socket,
        send: socket.send.bind(socket),
        on: socket.on.bind(socket),
        off: socket.off.bind(socket)
    };
}

使用


import {useSocket} from './useSocket'
/**
 * useSocket String 第一个参数 socket地址
 * 第二个参数 Object heartbeatInterval:心跳;reconnectInterval:重连间隔时间;maxReconnectAttempts:最大重连次数
 */
const {socket, send, on, off} = useSocket('ws://127.0.0.1:5000',{});

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Vue3中,我们可以通过封装Websocket类来实现对Websocket使用。通过引用和可以得知,在Vue3中使用Websocket可以实现实时数据传输。为了方便使用,我们可以封装一个好用的Websocket类。具体步骤如下: 1. 首先,安装Websocket的依赖,可以通过npm或yarn等包管理工具进行安装。 2. 创建一个Websocket类,该类应该包含Websocket的连接、发送消息和接收消息的方法。可以参考引用中提到的封装Websocket类的方法。 3. 在Vue3中,可以将Websocket封装成一个Vue插件,以便全局使用。具体步骤如下: - 创建一个插件文件,例如`websocket-plugin.js`。 - 在插件文件中,引入Websocket类并创建一个Vue插件对象。 - 在插件对象的`install`方法中,将Websocket实例挂载到Vue的原型上,以便在组件中可以通过`this.$websocket`来访问Websocket实例。 - 最后,导出该插件对象。 - 示例代码如下: ```javascript import Websocket from './websocket.js'; const WebsocketPlugin = { install(Vue) { Vue.prototype.$websocket = new Websocket('ws://localhost:8080'); }, }; export default WebsocketPlugin; ``` 4. 在Vue项目中,将该插件引入并使用。可以在`main.js`或其他入口文件中使用`app.use()`方法来安装该插件。示例代码如下: ```javascript import { createApp } from 'vue'; import App from './App.vue'; import WebsocketPlugin from './websocket-plugin.js'; const app = createApp(App); app.use(WebsocketPlugin); app.mount('#app'); ``` 通过以上步骤,我们就可以在Vue3中封装Websocket,并在全局范围内使用了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [基于Vue3封装一个好用的Websocket](https://blog.csdn.net/qq_27244301/article/details/130098672)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万水千山走遍TML

您的鼓励,将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值