uniapp 封装websocket 有重连 心跳功能 并全局使用
时间: 2023-12-22 11:06:35 浏览: 32
以下是一个示例代码,实现了Uniapp中封装WebSocket的功能,包括重连和心跳功能,并可以在全局使用。
```javascript
// utils/websocket.js
const HEARTBEAT_TIME = 30 * 1000 // 心跳时间间隔
class WebSocketUtil {
constructor(url, options = {}) {
this.url = url
this.options = options
this.socket = null
this.isReconnecting = false // 是否正在重连
this.heartbeatInterval = null // 心跳定时器
}
connect() {
return new Promise((resolve, reject) => {
this.socket = uni.connectSocket({
url: this.url,
...this.options,
success: () => {
this.initEvent()
resolve()
},
fail: reject,
})
})
}
initEvent() {
this.socket.onOpen(() => {
console.log('WebSocket连接已打开')
this.startHeartbeat() // 开始心跳
})
this.socket.onClose((e) => {
console.log('WebSocket连接已关闭', e)
this.stopHeartbeat() // 停止心跳
if (!this.isReconnecting) {
this.isReconnecting = true
this.reconnect() // 重连
}
})
this.socket.onError((e) => {
console.log('WebSocket连接发生错误', e)
this.stopHeartbeat() // 停止心跳
if (!this.isReconnecting) {
this.isReconnecting = true
this.reconnect() // 重连
}
})
this.socket.onMessage((res) => {
console.log('WebSocket收到消息', res)
})
}
reconnect() {
setTimeout(() => {
console.log('WebSocket正在重连...')
this.connect().then(() => {
console.log('WebSocket重连成功')
this.isReconnecting = false
}).catch(() => {
console.log('WebSocket重连失败')
this.reconnect()
})
}, 3000)
}
startHeartbeat() {
this.heartbeatInterval = setInterval(() => {
if (this.socket.readyState === 1) {
console.log('WebSocket发送心跳')
this.socket.send({ type: 'heartbeat' })
}
}, HEARTBEAT_TIME)
}
stopHeartbeat() {
clearInterval(this.heartbeatInterval)
}
}
export default {
install(Vue) {
const websocket = new WebSocketUtil('wss://example.com')
Vue.prototype.$websocket = websocket
websocket.connect()
},
}
```
使用时,在main.js中引入并注册即可:
```javascript
// main.js
import Vue from 'vue'
import App from './App.vue'
import websocket from './utils/websocket'
Vue.config.productionTip = false
Vue.use(websocket)
new Vue({
render: h => h(App),
}).$mount('#app')
```
在组件中,可以通过`this.$websocket`来获取WebSocket实例,然后进行发送消息等操作:
```javascript
// HelloWorld.vue
export default {
mounted() {
this.$websocket.socket.send({ type: 'hello' })
}
}
```