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

uni-app 封装websocket 心跳检测,开箱即用

class websocketUtils {constructor(url, needbeat, options = {}) {this.needbeat = needbeat;this.url = url;this.options = options;this.ws = null;this.heartbeatInterval = options.heartbeatInterval || 10000; // 心跳间隔,默认为10秒  this.reconnectInterval = options.reconnectInterval || 5000; // 重连间隔,默认为5秒  this.reconnectAttempts = options.reconnectAttempts || Infinity; // 最大重连次数,默认为无限次  this.reconnectCount = 0;this.initWebSocket();}initWebSocket() {this.ws = uni.connectSocket({url: this.url,success: () => {console.log('WebSocket连接成功');if (this.needbeat) {this.startHeartbeat();}this.onOpen();},fail: (err) => {console.error('WebSocket连接失败', err);this.reconnect();}});// 监听WebSocket接收到服务器的消息事件  this.ws.onMessage((result) => {// const textDecoder = new TextDecoder();// let text = textDecoder.decode(result.data)// console.log('自定义处理消息:',result);this.onMessage(result);// 收到消息后,可能需要重置心跳计时器  // 是否需要心跳选择器if (this.needbeat) {this.resetHeartbeat();}})// 监听WebSocket关闭事件  this.ws.onClose(res => {console.log('WebSocket连接已关闭', res);this.onClose();this.reconnect();});// 监听WebSocket错误事件  this.ws.onError(err => {console.error('WebSocket发生错误', err);this.onError(err);this.reconnect();});}// 发送消息  send(data) {if (this.ws) {this.ws.send({data: data,success: () => {console.log('消息发送成功');},fail: (err) => {console.error('消息发送失败', err);}})}}// 心跳检测  startHeartbeat() {this.heartbeatTimer = setInterval(() => {this.sendHeartbeat();}, this.heartbeatInterval);}// 重置心跳计时器  resetHeartbeat() {clearInterval(this.heartbeatTimer);this.startHeartbeat();}// 发送心跳消息  sendHeartbeat() {this.send('ping'); // 假设心跳消息为'ping'  }// 重连逻辑  reconnect() {if (this.reconnectCount < this.reconnectAttempts) {setTimeout(() => {this.initWebSocket();this.reconnectCount++;}, this.reconnectInterval);}}// 自定义事件处理  onOpen() {}onMessage(data) {}onClose() {}onError(err) {}// 关闭WebSocket连接  close() {if (this.ws) {this.ws.close({success: () => {console.log('WebSocket连接已关闭');},fail: (err) => {console.error("wss关闭失败->", err)}});clearInterval(this.heartbeatTimer);this.ws = null;}}
}
export default websocketUtils;

使用

let socket = new websocketUtils(wss_.url, false, {heartbeatInterval: 5000,reconnectInterval: 3000,reconnectAttempts: 5
});socket.onMessage = function(evt) {//获取消息
};socket.send(message);//发送消息
socket.close();//关闭sockett

http://www.lryc.cn/news/448853.html

相关文章:

  • ASP.NET Core8.0学习笔记(十九)——EF Core DbSet
  • Android Camera 预览角度和拍照保存图片角度相关
  • 新手如何使用Qt——方法使用
  • 友元运算符重载函数
  • 从0开始实现es6 promise类
  • XML 编码
  • AI周报(9.22-9.28)
  • 基于RealSense D435相机实现手部姿态重定向
  • js中防抖 debounce 节流 throttle 原理 从0手动实现
  • AIGC: 10 AI转文服务器的搭建过程记录
  • 性能测试1初步使用Jmeter
  • OpenGL ES 绘制一个三角形(2)
  • QT----Creater14.0,qt5.15无法启动调试,Launching GDB Debugger报红
  • 初试React前端框架
  • 华为OD机试真题---手机App防沉迷系统
  • 物流货运托运发货单二联三联打印软件定制 佳易王物流单管理系统操作教程
  • 代码随想录算法训练营| 找树左下角的值 、 路径总和 、 从中序与后序遍历序列构造二叉树
  • 【开源免费】基于SpringBoot+Vue.JS服装销售平台(JAVA毕业设计)
  • 人工智能与自然语言处理发展史
  • 0基础跟德姆(dom)一起学AI 机器学习01-机器学习概述
  • yakit使用教程(一,下载并进行基础配置)
  • 计算机毕业设计电影票购买网站 在线选票选座 场次订票统计 新闻留言搜索/springboot/javaWEB/J2EE/MYSQL数据库/vue前后分离小程序
  • DES、3DES 算法及其应用与安全性分析
  • TypeScript介绍和安装
  • NetworkPolicy访问控制
  • C++面向对象基础
  • 遥感图像变换检测实践上手(TensorRT+UNet)
  • Transformers 引擎,vLLM 引擎,Llama.cpp 引擎,SGLang 引擎,MLX 引擎
  • 牛顿迭代法求解x 的平方根
  • 端口隔离配置的实验