vue3 webSocket 封装及使用

news/2025/2/19 12:50:35/

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',{});

http://www.ppmy.cn/news/1233282.html

相关文章

纯css实现边界检测小球动画

文章目录 前言实现环境话不多说直接上代码后言 前言 hello world欢迎来到前端的新世界 &#x1f61c;当前文章系列专栏&#xff1a;css实现炫酷的动画 &#x1f431;‍&#x1f453;博主在前端领域还有很多知识和技术需要掌握&#xff0c;正在不断努力填补技术短板。(如果出现错…

接入电商数据平台官方开放平台API接口获取商品实时信息数据,销量,评论,详情页演示

要接入电商数据平台官方开放平台API接口获取商品实时信息数据、销量、评论和详情页演示&#xff0c;需要按照以下步骤进行操作&#xff1a; 找到可用的API接口&#xff1a;首先&#xff0c;需要找到支持查询商品信息的API接口。可以在电商数据平台的官方开放平台上查找相应的AP…

【python学习】基础篇-常用第三方库-requests库:用于发送各种类型的HTTP请求

在Python中&#xff0c;requests库是一个常用的HTTP请求库&#xff0c;用于发送各种类型的HTTP请求。 以下是一些基本的用法&#xff1a; 更多高级功能可以参考官方文档&#xff1a;https://docs.python-requests.org/ 发送GET请求 response requests.get(https://www.examp…

软件质量保护与测试(第2版)学习总结第十三章 集成测试

很多人都认为微软是一家软件开发公司&#xff0c;事实上我们是一家软件测试公司。 ---比尔盖茨 集成测试是在单元测试的基础上将多个模块组合在一起进行测试的过程。 13.1.1 区别 单元测试主要关注模块内部&#xff0c;系统测试则是在用户的角度来评价系统&#xff…

三点的最近距离

题目描述 题目中会给你三个整数 a,b,c,表示三个点在数轴上所处的位置。对于每一个点&#xff0c;你最多可以移动一次&#xff0c;也可以选择不移动&#xff0c;现在请你编写代码计算&#xff0c;移动后三个点的最小的距离和为多少&#xff1f; 输入输出格式 输入格式 一行三…

材料电磁参数综合测试解决方案-材料电磁参数测试系统 (100MHz-500GHz)

材料电磁参数测试系统 100MHz-500GHz 材料电磁参数测试系统测试频率范围覆盖100MHz&#xff5e;500GHz&#xff0c;可实现材料复介电常数、复磁导率等参数测试。系统由矢量网络分析仪、测试夹具、系统软件等组成&#xff0c;根据用户不同频率、材料类型的测试需求&#xff…

原来 TinyVue 组件库跨框架(Vue2、Vue3、React、Solid)是这样实现的?

本文由 TinyVue 组件库核心成员郑志超分享&#xff0c;首先分享了实现跨框架组件库的必要性&#xff0c;同时通过演示Demo和实际操作向我们介绍了如何实现一个跨框架的组件库。 前言 前端组件库跨框架是什么&#xff1f; 前端组件库跨框架是指在不同的前端框架&#xff08;如…