uniapp封装websocket以及心跳检测、重连

devtools/2024/10/18 7:55:35/

websocket 封装

在所需文件夹下建立websocketUtils.js文件,封装代码如下:

class websocketUtils {constructor(openId, time) {this.url = `wss://****` //ws地址 拼接一下 此处用的是openIdthis.data = nullthis.isOpenSocket = false //避免重复连接this.timeout = time //隔多久执行检测 单位秒(s)this.heartbeatInterval = null //检测服务器端是否还存活this.reconnectTimeOut = null //重连之后隔多久才再次重连try {return this.connectSocketInit()} catch (e) {console.log('===========连接错误捕获catch====================',e);this.isOpenSocket = falsethis.reconnect();}}// 创建websocket连接connectSocketInit() {this.socketTask = uni.connectSocket({url: this.url,header: {//头部可以添加所需字段如token'content-type': 'application/json'},success:()=>{console.log("============正准备建立websocket中================");// 返回实例return this.socketTask},});this.socketTask.onOpen((res) => {console.log("==============WebSocket连接正常=============");clearTimeout(this.reconnectTimeOut)clearInterval(this.heartbeatInterval)this.isOpenSocket = true;this.start();// 只有连接正常打开中 ,才能正常收到消息this.socketTask.onMessage((res) => {console.log(res.data,'===============接收===onMessage===============')//全局注册uniapp事件,在任何页面都能接受到uni.$emit('socketMessage', res)});})// 监听失败,再次打开 判断主动重连// uni.onSocketError((res) => {// 	console.log('==========WebSocket连接打开失败哦===============');//	this.isOpenSocket = false;//	this.reconnect();// });//  socket关闭了会执行 此处this.socketTask.onClose((e) => {console.log("========已经被关闭了====================",e)this.isOpenSocket = false;// 加了flag判断是否为手动(用户主动关闭)e && e.reason == 'user' ? '' : this.reconnect();})}//发送消息send(value){//  连接正常打开时 ,才能正常成功发送消息this.socketTask.send({data: value,async success() {console.log("===========消息发送成功===============");},});}//开启心跳检测start(){this.data={value:"发送心跳内容",method:"发送心跳方法名称"}this.heartbeatInterval = setInterval(()=>{console.log('======start====开启心跳检测====',this.data)this.send(JSON.stringify(this.data));},this.timeout * 1000)}//重新连接reconnect(){//停止发送心跳clearInterval(this.heartbeatInterval)//如果不是人为关闭的话,进行重连if(!this.isOpenSocket ){this.reconnectTimeOut = setTimeout(()=>{this.connectSocketInit();},3000)}}// 关闭 WebSocket 连接closeSocket(reason = '关闭') {const _this = thisthis.socketTask.close({reason,success() {_this.data = null_this.isOpenSocket = false_this.socketTask = nullclearTimeout(_this.reconnectTimeOut)clearInterval(_this.heartbeatInterval)console.log('===============关闭 WebSocket 成功===================')},fail() {console.log('===================关闭 WebSocket 失败=====================')}})}//将获取的消息导出外部exportMessage(callback) {this.socketTask.onMessage((res) => {console.log(res,'===============exportMessage============')return callback(res)})}
}module.exports = websocketUtils 

页面引入使用 

全局引入:

1.在main.js中引入,并全局注册

//引入websocket文件
import websocketUtils from '@/utils/websocketUtils.js'//挂载并开启websocket
Vue.prototype.$socketUtils = new websocketUtils("*******",10)

 2.指定页面中使用

// 发送消息
let data={value:"发送的value"}
this.$socketUtils.send(JSON.stringify(data));// 接收消息
this.$socketUtils.exportMessage(res=>{console.log(res);
})
 单页面使用引入:
<!--  页面  -->
<template><view class='e-about-operation-wrap'></view>
</template><script>import websocketUtils  from '@/utils/websocketUtils.js'const app = getApp()export default {name: 'ESign',components: {},data() {return { };},onLoad: function(option) {},onShow: function() {//在uniapp全局中定义了socketWBObj变量app.globalData.socketWBObj = new websocketUtils(this.user.loginInfo.openId,10)//监听获取消息uni.$on('socketMessage', this.wbSocketGetMsg)//方法获取收到的消息app.globalData.socketWBObj.exportMessage(res => {console.warn(res);})},onHide: function() {},onUnload(e) {},created() {},mounted() {},methods: {wbSocketGetMsg(res){const _this = thisconsole.log(res,'======wbSocketGetMsg==========')// 关闭连接if (app.globalData.socketWBObj) {app.globalData.socketWBObj.closeSocket('user')}}},watch: {},computed: {},}
</script>
<style lang='scss' scoped>
.e-about-operation-wrap{}
</style>


http://www.ppmy.cn/devtools/7051.html

相关文章

搭建电商网站跨境电商独立站|网上商城接口/电商数据接口详情

电商运营中&#xff0c;数据分析这项工作越来越重要&#xff0c;许多品牌方也越来越热衷去做电商数据分析。不过&#xff0c;全面的数据该如何获取呢&#xff0c;此时&#xff0c;电商数据接口的重要性便凸显出来了。 监控范围广&#xff1a; 可监控的范围包含京东、天猫、淘…

【2024】深度学习配置环境常见报错,持续更新中....

No such file or directory: ‘:/usr/local/cuda-10.1:/usr/local/cuda-10.1/bin/nvcc‘: 确保CUDA正常后&#xff0c;直接运行以下代码&#xff1a; export CUDA_HOME/usr/local/cuda详细原因参照&#xff0c;安装mmcv-full时报错&#xff1a;Could not build wheels for mm…

黑客知识了解

ipc$ 利用139&#xff0c;445端口 弱口令&#xff1a;admin,123456,root 容易被破解 命令 内部命令&#xff08;系统自带命令&#xff09; dir,tree,notepad 外部命令&#xff08;你自己下载的命令&#xff09; python webshell 网页木马 SQL注入 sql 结构化查询语言 …

【ThinkPHP框架教程·Part-02】开发规范和目录结构

文章目录 一、开发规范1、目录和文件的规范2、函数和类、属性命名规范3、常量与配置的规范4、数据表和字段的规范 二、目录结构1、单应用模式目录结构图&#xff08;默认&#xff09;2、多应用模式目录结构图&#xff08;自定义&#xff09;3、仅允许public目录对外访问4、其他…

ChatGPT实用指南2024

随着ChatGPT技术的演进&#xff0c;越来越多的人开始在工作中利用此工具。以下是关于ChatGPT的实用指南&#xff0c;适合不太熟悉此技术的朋友参考。 一、ChatGPT概述 1. ChatGPT是什么&#xff1f; ChatGPT是基于OpenAI开发的GPT大型语言模型的智能对话工具。它能够通过自然语…

DBeaver(其他可视化工具一样的逻辑)连接IoTDBDriver教程

DBeaver(其他可视化工具一样的逻辑&#xff09;连接IoTDBDriver教程 一 下载安装 官网下载链接&#xff1a; https://iotdb.apache.org/Download/二 安装 DBeaver 三 连接 点确定 选择IoTDB驱动 点击下一步 点击测试链接 点击确定 注意: 需要自己写查询语句才能看见…

Golang | Leetcode Golang题解之第36题有效的数独

题目&#xff1a; 题解&#xff1a; func isValidSudoku(board [][]byte) bool {var rows, columns [9][9]intvar subboxes [3][3][9]intfor i, row : range board {for j, c : range row {if c . {continue}index : c - 1rows[i][index]columns[j][index]subboxes[i/3][j/3]…

消息转化器(解决由于后端给前端响应的格式中不能处理Long类型,因为js只会处理前16位,这样会导致后面的精度丢失)

问题描述&#xff1a;由于后端给前端响应的格式中不能处理Long类型&#xff0c;因为js只会处理前16位&#xff0c;这样会导致后面的精度丢失。 解决方法&#xff0c;将后端响应给前端的数据转化位JSON格式&#xff0c;将long类型的序列化一下 下面为具体方法(JAVA对象转化为J…