复制import {UserManager} from "@/utils/userManager.js";
class webSocketClass {
constructor(url="ws://127.0.0.1:8088/",time=3) {
this.url = url
this.filterMessagesList = [""];
this.data = null
this.heartbeatCheckData = {}
this.isCreate = false
this.isConnect = false
this.isInitiative = false
this.timeoutNumber = time
this.heartbeatTimer = null
this.reconnectTimer = null
this.socketExamples = null
this.againTime = 3
}
initSocket(gameId) {
const _this = this
this.socketExamples = uni.connectSocket({
url: `${_this.url}?gameId=${gameId}&$userId=${UserManager.shared().userInfo.userId}`,
header: {
'content-type': 'application/json',
token: UserManager.shared().userInfo ? UserManager.shared().userInfo.token : ''
},
success: (res) => {
_this.isCreate = true
console.log(res)
},
fail: (rej) => {
console.error(rej)
_this.isCreate = false
}
})
this.createSocket()
}
createSocket() {
var _this = this
if (this.isCreate) {
console.log('WebSocket 开始初始化')
try {
this.socketExamples.onOpen(() => {
console.log('WebSocket 连接成功')
this.isConnect = true
clearInterval(this.heartbeatTimer)
clearTimeout(this.reconnectTimer)
this.heartbeatCheck()
})
this.socketExamples.onMessage((res) => {
console.log('收到消息---',res.data)
if (_this.filterMessagesList.includes(res.data)) {
console.log(`信息:${res.data}--在过滤列表中不进行推送`)
}else{
uni.$emit('message', res)
}
})
this.socketExamples.onClose(() => {
console.log('WebSocket 关闭了')
this.isConnect = false
this.reconnect()
})
this.socketExamples.onError((res) => {
console.log('WebSocket 出错了')
console.log(res)
this.isInitiative = false
})
} catch (error) {
console.warn(error)
}
} else {
console.warn('WebSocket 初始化失败!')
}
}
isEmptyObject(value) {
return typeof value === 'object' && Object.keys(value).length === 0;
}
sendMsg(value) {
if (!this.isEmptyObject(value)){
value["userId"] = UserManager.shared().userInfo ? UserManager.shared().userInfo.userId : ''
}
const param = JSON.stringify(value)
return new Promise((resolve, reject) => {
this.socketExamples.send({
data: param,
success() {
console.log('消息发送成功')
resolve(true)
},
fail(error) {
console.log('消息发送失败')
reject(error)
}
})
})
}
heartbeatCheck() {
var _this = this
console.log('开启心跳')
this.heartbeatTimer = setInterval(() => {
_this.sendMsg(_this.heartbeatCheckData)
}, _this.timeoutNumber * 1000)
}
reconnect() {
clearTimeout(this.reconnectTimer)
clearInterval(this.heartbeatTimer)
if (!this.isInitiative) {
this.reconnectTimer = setTimeout(() => {
this.initSocket()
}, this.againTime * 1000)
}
}
closeSocket(reason = '关闭') {
const _this = this
this.socketExamples.close({
reason,
success() {
_this.data = null
_this.isCreate = false
_this.isConnect = false
_this.isInitiative = true
_this.socketExamples = null
clearInterval(_this.heartbeatTimer)
clearTimeout(_this.reconnectTimer)
console.log('关闭 WebSocket 成功')
},
fail(error) {
console.log('关闭 WebSocket 失败',error)
}
})
}
}
export {webSocketClass}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理