当前位置: 代码网 > it编程>前端脚本>Vue.js > websocket在vue3+ts中的封装及使用方法

websocket在vue3+ts中的封装及使用方法

2024年08月01日 Vue.js 我要评论
wensocket.ts文件中。

wensocket.ts文件中

// src/utils/websocket.ts
import { ref, onunmounted } from 'vue';

interface websocketoptions {
    url: string;
    protocols?: string | string[];
    reconnecttimeout?: number;
}

class websocketservice {
    private ws: websocket | null = null;
    private callbacks: { [key: string]: function[] } = {};
    private reconnecttimeoutms: number = 5000; // 默认5秒重连间隔

    constructor(private options: websocketoptions) {}

    public open(): void {
        this.ws = new websocket(this.options.url, this.options.protocols)
        this.ws.addeventlistener('open', this.handleopen);
        this.ws.addeventlistener('message', this.handlemessage);
        this.ws.addeventlistener('error', this.handleerror);
        this.ws.addeventlistener('close', this.handleclose);
    }

    public close(isactiveclose = false): void {
        if (this.ws) {
            this.ws.close();
            if (!isactiveclose) {
                settimeout(() => this.reconnect(), this.reconnecttimeoutms);
            }
        }
    }

    public reconnect(): void {
        this.open();
    }

    public on(event: 'message', callback: (data: any) => void): void;
    public on(event: 'open' | 'error' | 'close', callback: () => void): void;
    public on(event: string, callback: (...args: any[]) => void): void {
        if (!this.callbacks[event]) {
            this.callbacks[event] = [];
        }
        this.callbacks[event].push(callback);
    }

    private handleopen = (): void => {
        console.log('websocket连接已建立');
        if (this.callbacks.open) {
            this.callbacks.open.foreach((cb) => cb());
        }
    };

    private handlemessage = (event: messageevent): void => {
        const data = json.parse(event.data);
        console.log('websocket接收到消息:', data);
        if (this.callbacks.message) {
            this.callbacks.message.foreach((cb) => cb(data));
        }
    };

    private handleerror = (error: event): void => {
        console.error('websocket错误:', error);
        if (this.callbacks.error) {
            this.callbacks.error.foreach((cb) => cb(error));
        }
    };

    private handleclose = (): void => {
        console.log('websocket连接已关闭');
        if (this.callbacks.close) {
            this.callbacks.close.foreach((cb) => cb());
            if (!this.options.reconnecttimeout) {
                this.reconnect();
            }
        }
    };

    public send(data: any): void {
        if (this.ws && this.ws.readystate === websocket.open) {
            this.ws.send(json.stringify(data));
        } else {
            console.warn('尝试发送消息时websocket未连接');
        }
    }
}

export default function usewebsocket(options: websocketoptions) {
    const wsservice = new websocketservice(options);

    onunmounted(() => {
        wsservice.close(true);
    });

    return {
        open: wsservice.open.bind(wsservice),
        close: wsservice.close.bind(wsservice),
        reconnect: wsservice.reconnect.bind(wsservice),
        on: wsservice.on.bind(wsservice),
        send: wsservice.send.bind(wsservice)
    };

使用

import usewebsocket from '@/utils/websocket';//引入websocket.ts文件

import config from '@/config' //引入公共配置文件

const wsoptions = {
  url: config.wbbaseurl,
};

const { open, close, reconnect, on, send } = usewebsocket(wsoptions);

onmounted(() => {
  open();//在onmounted钩子中调用open函数,链接websocket

  // 注册消息接收处理函数
  on('message', (data) => {
    receivedmessage = data;
    console.log(data)
  });
});

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com