当前位置: 首页 > news >正文

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',{});
http://www.lryc.cn/news/246486.html

相关文章:

  • 记录vscode常用插件集合(extensions)
  • 正则表达式详解
  • 【限时免费】20天拿下华为OD笔试之【双指针】2023Q1A-两数之和绝对值最小【欧弟算法】全网注释最详细分类最全的华为OD真题题解
  • expect脚本在自动化部署中的具体应用案例
  • 【Java+SQL Server】前后端连接小白教程
  • Xilinx Zynq-7000系列FPGA多路视频处理:图像缩放+视频拼接显示,提供工程源码和技术支持
  • Web语言基础课程期末代做
  • Scanner常用知识点
  • uniapp页面使用多个echarts出现数据渲染错乱问题解决
  • PHP连接数据库 错误抑制 三元运算符 学习资料
  • 5G智慧工地整体解决方案:文件全文115页,附下载
  • 数据结构 / 内存的动态申请和释放
  • Android手电筒、闪光灯、torch、flash
  • C语言--每日选择题--Day26
  • [ACTF2020 新生赛]BackupFile
  • WPF面试题:WPF绘图技术介绍
  • 三、Lua变量
  • C#每天复习一个重要小知识day4:枚举的概念/申明/使用
  • C++:对象模型和this指针
  • 碳酸氢锂/硫酸锂溶液纯化除钙镁解决方案
  • 消失的数字,旋转数组(leetcode 一题多解)
  • 肠道菌群16s检测粪便采样工具包 粪便采样套装
  • 实现领域驱动设计-07-领域服务
  • 井盖位移传感器厂家批发,守护井盖安全
  • python命令行交互 引导用户选择宠物
  • Leetcode—167.两数之和 II - 输入有序数组【中等】
  • MybatisPlus改造逻辑删除有多方便
  • 希尔伯特变换-matlab仿真
  • python字典的基本操作详解
  • [ CSS ] 内容超出容器后 以...省略