- 使用 SocketTask 的方式去管理 webSocket 链接,每一条链路的生命周期都更加可控
- 可实现主动建立连接、心跳防断线机制、断线主动重连、提供主动断开的方法
一、如何使用 (uniapp Vue3)
<template>
</template>
<script setup>
import WS from './websocket'
import { onLoad, onUnload } from '@dcloudio/uni-app'
let ws = null
onLoad((options) => {
ws = new WS({
data: { userId: options.userId },
onConnected: () => {
},
onMessage: (data) => {
}
})
})
function sendMsg() {
uni.request({
url: '后端url',
data: {...},
success: () => {
}
})
}
onUnload(() => {
ws.close()
})
</script>
二、websocket类代码
const interval = 5000
const maxReconnectMaxTime = 5
export default class WS {
constructor(options) {
this.options = options
this.socketTask = null
this.normalCloseFlag = false
this.reconnectTime = 1
this.reconnectTimer = null
this.heartTimer = null
this.initWS()
this.close = () => {
this.normalCloseFlag = true
this.socketTask.close()
clearInterval(this.heartTimer)
clearTimeout(this.reconnectTimer)
}
}
initWS() {
const url = 'wss://后端url' + this.options.data.userId
this.socketTask = uni.connectSocket({ url, success() {} })
this.watchWS()
}
watchWS() {
this.socketTask.onOpen(() => {
console('websocket连接成功!')
this.options.onConnected()
this.reconnectTime = 1
this.onHeartBeat()
this.onMessage()
uni.hideLoading()
})
this.socketTask.onError(() => {
this.socketTask.close()
})
this.socketTask.onClose((res) => {
if (!this.normalCloseFlag) {
this.onDisconnected(res)
}
})
}
onMessage() {
this.socketTask.onMessage((res) => {
if (res.data) {
this.options.onMessage(JSON.parse(res.data))
} else {
console('未监听到消息:原因:', JSON.stringify(res))
}
})
}
onDisconnected(res) {
console('websocket断开连接,原因:', JSON.stringify(res))
clearInterval(this.heartTimer)
uni.showLoading({ title: '消息收取中…' })
this.onReconnect()
}
onReconnect() {
clearTimeout(this.reconnectTimer)
if (this.reconnectTime < maxReconnectMaxTime) {
this.reconnectTimer = setTimeout(() => {
console.log(`第【${this.reconnectTime}】次重新连接中……`)
this.initWS()
this.reconnectTime++
}, interval)
} else {
uni.showModal({
title: '温馨提示',
content: '服务器开小差啦~请返回聊天列表重试',
showCancel: false,
confirmText: '我知道了',
success: () => {
uni.navigateBack()
}
})
}
}
onHeartBeat() {
this.heartTimer = setInterval(() => {
this.socketTask.send({
data: `heart:${this.options.data.userId}`,
success() {
console.log('心跳发送成功!')
}
})
}, interval)
}
}
本网站是一个以CSS、JavaScript、Vue、HTML为核心的前端开发技术网站。我们致力于为广大前端开发者提供专业、全面、实用的前端开发知识和技术支持。
在本网站中,您可以学习到最新的前端开发技术,了解前端开发的最新趋势和最佳实践。我们提供丰富的教程和案例,让您可以快速掌握前端开发的核心技术和流程。
本网站还提供一系列实用的工具和插件,帮助您更加高效地进行前端开发工作。我们提供的工具和插件都经过精心设计和优化,可以帮助您节省时间和精力,提升开发效率。
除此之外,本网站还拥有一个活跃的社区,您可以在社区中与其他前端开发者交流技术、分享经验、解决问题。我们相信,社区的力量可以帮助您更好地成长和进步。
在本网站中,您可以找到您需要的一切前端开发资源,让您成为一名更加优秀的前端开发者。欢迎您加入我们的大家庭,一起探索前端开发的无限可能!