export default {
url: xxx, // WebSocket的url
data: null,
isCreate: false,
isConnect: false, // 是否已经连接
isInitiative: false, // 是否主动断开
timeoutNumber: 30, // 心跳检测间隔(单位秒)
heartbeatTimer: null, // 心跳检测定时器
reconnectTimer: null, // 断线重连定时器
socketExamples: null, // websocket实例
againTime: 3, // 重连等待时间(单位秒)
// 初始化websocket连接
createSocket(token) {
const self = this
try {
self.socketExamples = uni.connectSocket({
url: xxx,
success: () => {
self.isCreate = true
},
fail: () => {
self.isCreate = false
}
})
} catch (err) {
console.log(err)
console.log('websocket connection is abnormal, reconnecting...')
self.reconnect(token)
}
self.initSocket()
},
// 创建websocket连接
initSocket() {
const self = this
if (!self.isCreate) return
self.socketExamples.onOpen(() => {
console.log('WebSocket 连接成功')
self.isConnect = true
self.heartbeatTimer && clearInterval(self.heartbeatTimer)
self.reconnectTimer && clearTimeout(self.reconnectTimer)
// 打开心跳检测
self.heartbeatCheck()
})
// 监听 WebSocket 接受到服务器的消息事件
self.socketExamples.onMessage(({ data }) => {
// console.log('收到消息')
// console.log(res)
uni.$emit('message', JSON.parse(data))
})
// 监听 WebSocket 连接关闭事件
self.socketExamples.onClose(() => {
console.log('WebSocket 关闭了')
self.isConnect = false
self.reconnect()
})
// 监听 WebSocket 错误事件
self.socketExamples.onError((res) => {
console.log('WebSocket 出错了')
console.log(res)
self.isInitiative = false
})
},
// 发送消息
sendMsg(value) {
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() {
this.data = {
type: 10
}
this.heartbeatTimer = setInterval(() => {
this.sendMsg(this.data)
}, this.timeoutNumber * 1000)
},
// 重新连接
reconnect() {
// 停止发送心跳
this.reconnectTimer && clearTimeout(this.reconnectTimer)
this.heartbeatTimer && clearInterval(this.heartbeatTimer)
// 如果不是人为关闭的话,进行重连
if (!this.isInitiative) {
this.reconnectTimer = setTimeout(() => {
this.createSocket()
}, this.againTime * 1000)
}
},
// 关闭 WebSocket 连接
closeSocket(reason = '关闭') {
const self = this
this.socketExamples.close({
reason,
success() {
self.data = null
self.isCreate = false
self.isConnect = false
self.isInitiative = true
self.socketExamples = null
clearInterval(self.heartbeatTimer)
clearTimeout(self.reconnectTimer)
// console.log('关闭 WebSocket 成功')
},
fail() {
console.log('关闭 WebSocket 失败')
}
})
}
}
websocket在uniapp上的使用(心跳机制)
于 2023-05-24 15:48:21 首次发布