封装一个websocket,支持断网重连、心跳检测,拿来开箱即用

本文主要是介绍封装一个websocket,支持断网重连、心跳检测,拿来开箱即用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

封装一个websocket,支持断网重连、心跳检测

代码封装

编写 WebSocketClient.js

import { EventDispatcher } from './dispatcher'export class WebSocketClient extends EventDispatcher {constructor(url) {console.log(url, 'urlurl')super()this.url = url}// #socket实例socket = null// #重连次数reconnectAttempts = 0// #最大重连数maxReconnectAttempts = 5// #重连间隔reconnectInterval = 10000 // 10 seconds// #发送心跳数据间隔heartbeatInterval = 1000 * 30// #计时器idheartbeatTimer = undefined// #彻底终止wsstopWs = false// >生命周期钩子onopen(callBack) {this.addEventListener('open', callBack)}onmessage(callBack) {this.addEventListener('message', callBack)}onclose(callBack) {this.addEventListener('close', callBack)}onerror(callBack) {this.addEventListener('error', callBack)}// >消息发送send(message) {if (this.socket && this.socket.readyState === WebSocket.OPEN) {this.socket.send(message)} else {console.error('[WebSocket] 未连接')}}// !初始化连接connect() {if (this.reconnectAttempts === 0) {this.log('WebSocket', `初始化连接中...          ${this.url}`)}if (this.socket && this.socket.readyState === WebSocket.OPEN) {return}this.socket = new WebSocket(this.url)// !websocket连接成功this.socket.onopen = (event) => {this.stopWs = false// 重置重连尝试成功连接this.reconnectAttempts = 0// 在连接成功时停止当前的心跳检测并重新启动this.startHeartbeat()this.log('WebSocket', `连接成功,等待服务端数据推送[onopen]...     ${this.url}`)this.dispatchEvent('open', event)}this.socket.onmessage = (event) => {this.dispatchEvent('message', event)this.startHeartbeat()}this.socket.onclose = (event) => {if (this.reconnectAttempts === 0) {this.log('WebSocket', `连接断开[onclose]...    ${this.url}`)}if (!this.stopWs) {this.handleReconnect()}this.dispatchEvent('close', event)}this.socket.onerror = (event) => {if (this.reconnectAttempts === 0) {this.log('WebSocket', `连接异常[onerror]...    ${this.url}`)}this.closeHeartbeat()this.dispatchEvent('error', event)}}// > 断网重连逻辑handleReconnect() {if (this.reconnectAttempts < this.maxReconnectAttempts) {this.reconnectAttempts++this.log('WebSocket',`尝试重连... (${this.reconnectAttempts}/${this.maxReconnectAttempts})       ${this.url}`)setTimeout(() => {this.connect()}, this.reconnectInterval)} else {this.closeHeartbeat()this.log('WebSocket', `最大重连失败,终止重连: ${this.url}`)}}// >关闭连接close() {if (this.socket) {this.stopWs = truethis.socket.close()this.socket = nullthis.removeEventListener('open')this.removeEventListener('message')this.removeEventListener('close')this.removeEventListener('error')}this.closeHeartbeat()}// >开始心跳检测 -> 定时发送心跳消息startHeartbeat() {if (this.stopWs) returnif (this.heartbeatTimer) {this.closeHeartbeat()}this.heartbeatTimer = setInterval(() => {if (this.socket) {this.socket.send(JSON.stringify({ type: 'heartBeat', data: {} }))this.log('WebSocket', '送心跳数据...')} else {console.error('[WebSocket] 未连接')}}, this.heartbeatInterval)}// >关闭心跳closeHeartbeat() {clearInterval(this.heartbeatTimer)this.heartbeatTimer = undefined}
}

引用的 dispatcher.js 源码

import { Log } from './log'export class EventDispatcher extends Log {constructor() {super()this.listeners = {}}addEventListener(type, listener) {if (!this.listeners[type]) {this.listeners[type] = []}if (this.listeners[type].indexOf(listener) === -1) {this.listeners[type].push(listener)}}removeEventListener(type) {this.listeners[type] = []}dispatchEvent(type, data) {const listenerArray = this.listeners[type] || []if (listenerArray.length === 0) returnlistenerArray.forEach((listener) => {listener.call(this, data)})}
}

上面还用到了一个 log.js ,用于美化控制台打印的,这个文件在其他地方也通用

export class Log {static console = truelog(title, text) {if (!Log.console) returnconst color = '#09c'console.log(`%c ${title} %c ${text} %c`,`background:${color};border:1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`,`border:1px solid ${color}; padding: 1px; border-radius: 0 2px 2px 0; color: ${color};`,'background:transparent')}closeConsole() {Log.console = false}
}

至此一个 WebSocket 就封装好了

使用方法

首先使用node编写一个后端服务,用于 WebSocket 连接

需要安装一下 ws

npm install ws
const WebSocket = require("ws");const wss = new WebSocket.Server({port: 3200});console.log("服务运行在http://localhost:3200/");wss.on("connection", (ws) => {console.log("[服务器]:连接成功");ws.send(`[websocket云端]您已经连接云端!等待数据推送~`);ws.on("message", (res) => {ws.send(`[websocket云端]收到消息:${res.toString()}`);});ws.on("close", () => {console.log("[服务器]:连接已关闭~");});
});

然后我这里编写了一个简单的demo页面

<template><div><el-button type="primary" @click="connection">创建连接</el-button><el-button type="danger" @click="close">关闭连接</el-button><el-input v-model="message" placeholder="placeholder"></el-input><el-button type="primary" @click="send">发送消息</el-button><ul><li v-for="(item, index) in messageList" :key="index">{{ item }}</li></ul></div>
</template><script>
import { WebSocketClient } from '@/utils/WebSocketClient'export default {data() {return {message: '',messageList: [],ws: null,}},methods: {connection() {if (this.ws) {this.close()}this.ws = new WebSocketClient('ws://localhost:3200')this.setupWebSocketListeners()this.ws.connect()},close() {if (this.ws) {this.ws.close()this.ws = null}},send() {if (this.ws) {this.ws.send(this.message)}},setupWebSocketListeners() {this.ws.onmessage((msg) => {this.ws.log('WebSocketClient', msg.data)this.messageList.push(msg.data)})this.ws.onopen(() => {this.ws.log('WebSocketClient', '连接已打开')})this.ws.onclose(() => {this.ws.log('WebSocketClient', '连接已关闭')})this.ws.onerror((error) => {this.ws.log('WebSocketClient', '连接错误')console.error(error)})},},mounted() {this.connection()},
}
</script>

初次连接

image-20240531100922169

消息发送

image-20240531100944165

关闭连接后,消息就无法发送了

image-20240531101029443

再次连接

image-20240531101057517

这篇关于封装一个websocket,支持断网重连、心跳检测,拿来开箱即用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1020486

相关文章

鸿蒙中Axios数据请求的封装和配置方法

《鸿蒙中Axios数据请求的封装和配置方法》:本文主要介绍鸿蒙中Axios数据请求的封装和配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1.配置权限 应用级权限和系统级权限2.配置网络请求的代码3.下载在Entry中 下载AxIOS4.封装Htt

关于WebSocket协议状态码解析

《关于WebSocket协议状态码解析》:本文主要介绍关于WebSocket协议状态码的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录WebSocket协议状态码解析1. 引言2. WebSocket协议状态码概述3. WebSocket协议状态码详解3

SpringKafka消息发布之KafkaTemplate与事务支持功能

《SpringKafka消息发布之KafkaTemplate与事务支持功能》通过本文介绍的基本用法、序列化选项、事务支持、错误处理和性能优化技术,开发者可以构建高效可靠的Kafka消息发布系统,事务支... 目录引言一、KafkaTemplate基础二、消息序列化三、事务支持机制四、错误处理与重试五、性能优

SpringBoot中封装Cors自动配置方式

《SpringBoot中封装Cors自动配置方式》:本文主要介绍SpringBoot中封装Cors自动配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录SpringBoot封装Cors自动配置背景实现步骤1. 创建 GlobalCorsProperties

Java导入、导出excel用法步骤保姆级教程(附封装好的工具类)

《Java导入、导出excel用法步骤保姆级教程(附封装好的工具类)》:本文主要介绍Java导入、导出excel的相关资料,讲解了使用Java和ApachePOI库将数据导出为Excel文件,包括... 目录前言一、引入Apache POI依赖二、用法&步骤2.1 创建Excel的元素2.3 样式和字体2.

JAVA封装多线程实现的方式及原理

《JAVA封装多线程实现的方式及原理》:本文主要介绍Java中封装多线程的原理和常见方式,通过封装可以简化多线程的使用,提高安全性,并增强代码的可维护性和可扩展性,需要的朋友可以参考下... 目录前言一、封装的目标二、常见的封装方式及原理总结前言在 Java 中,封装多线程的原理主要围绕着将多线程相关的操

Java springBoot初步使用websocket的代码示例

《JavaspringBoot初步使用websocket的代码示例》:本文主要介绍JavaspringBoot初步使用websocket的相关资料,WebSocket是一种实现实时双向通信的协... 目录一、什么是websocket二、依赖坐标地址1.springBoot父级依赖2.springBoot依赖

一文教你解决Python不支持中文路径的问题

《一文教你解决Python不支持中文路径的问题》Python是一种广泛使用的高级编程语言,然而在处理包含中文字符的文件路径时,Python有时会表现出一些不友好的行为,下面小编就来为大家介绍一下具体的... 目录问题背景解决方案1. 设置正确的文件编码2. 使用pathlib模块3. 转换路径为Unicod

定价129元!支持双频 Wi-Fi 5的华为AX1路由器发布

《定价129元!支持双频Wi-Fi5的华为AX1路由器发布》华为上周推出了其最新的入门级Wi-Fi5路由器——华为路由AX1,建议零售价129元,这款路由器配置如何?详细请看下文介... 华为 Wi-Fi 5 路由 AX1 已正式开售,新品支持双频 1200 兆、配有四个千兆网口、提供可视化智能诊断功能,建

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形