省流
- 不要用
uni.xxx
那一套,用socketTask = await uni.connectSocket({})
的socketTask
去控制
业务逻辑描述
- 第一次进入应用主页,连接
WebSocket
- 手机熄屏之后,断开当前连接的
WebSocket
- 手机亮屏之后,再次进入应用后,重新连接
WebSocket
服务
问题
-
亮屏之后,再次进入应用,WebSocket 会累加,导致我发送的心跳包:
-
第一次熄屏亮起,会在短时间内发送两次
-
第二次熄屏亮起,会在短时间内发送三次
-
…累加
问题截图
问题代码
大概就是这套逻辑
用的都是 uni.xxx
这套,问题就出现在这里了
import { handleSocketMessage } from './websocketUtils'
import Nav2Login from '@/utils/request/modelNavigateToLogin'
let socketOpen = false
let socketMsgQueue: any = []
let heartbeatTimer: any | null = null
async function startWebsocketServer() {
if (heartbeatTimer) {
clearInterval(heartbeatTimer)
heartbeatTimer = null
}
if (socketOpen) {
await closeWebSocket()
}
await uni
.connectSocket({
url: WS_URL,
})
.then((res) => {
})
/**
* 问题:
* https://ask.dcloud.net.cn/question/149762
*/
uni.onSocketOpen(function (res: any) {
socketOpen = true
for (var i = 0; i < socketMsgQueue.length; i++) {
sendSocketMessage(socketMsgQueue[i])
}
socketMsgQueue = []
})
/**
* 这里会有熄屏累积次数的效果
*/
uni.onSocketMessage(function (res) {
console.log('收到服务器内容:' + res.data)
handleSocketMessage(res.data)
})
}
function sendSocketMessage(msg: any) {
if (socketOpen) {
uni.sendSocketMessage({
data: msg,
})
} else {
socketMsgQueue.push(msg)
}
}
/**
* 关闭WebSocket连接
*/
export function closeWebSocket() {
return new Promise((resolve, reject) => {
uni.closeSocket({
success: function (res) {
console.log('WebSocket关闭成功!:>>', res)
socketOpen = false
clearInterval(heartbeatTimer)
heartbeatTimer = null
console.log('清除心跳定时器')
resolve('Close Socket Success')
},
fail: function (res) {
console.log('WebSocket关闭失败!:>>', res)
reject('Close Socket Reject')
},
complete: () => {
// console.log('complete')
},
})
})
}
export default startWebsocketServer
解决之后的截图
解决的代码框架,参考官方文档
let socketTask: any = null
// complete: (res) => {}, 一定要有
socketTask = await uni.connectSocket({
url: WS_URL,
complete: (res) => {},
})
socketTask.onOpen(() => {})
socketTask.onMessage((res: any) => {})
socketTask.close({
success: (res: any) => {},
fail: (res: any) => {},
})