app.vue页面
里面的message.type 是和后台商量的类型。
1. websocket是进小程序就要启动的,在onLaunch里面但是肯定是在用户登录之后才启动,不然要报错。
2. 在onShow里面监听了一个emit,在用户登录之后,要启动websocket。
<script>
export default {
data() {
return {
wsUrl: "wss://***.****.com/wss/",
lockReconnect: false, // 避免重复连接
formId: null,
toId: null,
heartCheck : {
timeout: 30000,
timeoutObj: null,
serverTimeoutObj: null,
reset: () => {
clearTimeout(this.heartCheck.timeoutObj);
clearTimeout(this.heartCheck.serverTimeoutObj);
return this.heartCheck;
},
start: () => {
this.heartCheck.timeoutObj = setTimeout(() => {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
let heart = {
type: "heart",
fromId: this.formId
}
this.$store.state.wss.send({
data: JSON.stringify(heart),
success: () => {
// console.log("发送一次心跳包", heart);
}
})
this.heartCheck.serverTimeoutObj = setTimeout(() => {
this.$store.state.wss.onOpen(_ => {
this.$store.state.wss.close()
})
}, 70000) // 这里因为后台是60秒没反应就关闭,所以前端设置的是70秒关闭
}, this.heartCheck.timeout)
}
}
}
},
onLaunch: function() {
console.log('App Launch')
if(uni.getStorageSync('userInfo')) {
this.createSocket(this.wsUrl)
this.getMessageNum()
}
},
onShow: function() {
this.formId = uni.getStorageSync('userInfo').id
uni.$on('openSocket', (data) => {
this.formId = data.user_id
this.createSocket(this.wsUrl)
this.getMessageNum()
})
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
this.$store.state.wss.onOpen(_ => {
this.$store.state.wss.close()
})
},