1、新建websocket.js
import store from '@/store'
export default class WebsocketTask{
constructor(url,time){
this.url = url
this.data = null
this.isOpenSocket = false
// 心跳检测
this.timeout = time
this.heartbeat = null
try{
return this.connectSocketInit()
}catch(e){
this.isOpenSocket = false
this.reconnect();
}
}
connectSocketInit(){
this.socketTask = uni.connectSocket({
url: this.url,
header: {
'Authorization':'Bearer '+ store.state.user.token
},
success:(success)=>{
console.log(success)
},
fail:(fail)=>{
console.log(fail)
},
complete: (complete)=> {
console.log(complete)
}
})
this.socketTask.onOpen((res)=>{
clearTimeout(this.heartbeat);
this.isOpenSocket = true;
this.start();
this.socketTask.onMessage((res)=>{
console.log(res)
})
})
this.socketTask.onClose(()=>{
this.isOpenSocket = false;
this.reconnect();
})
}
//发送消息
send(data){
this.socketTask.send({
data,
})
}
//开启心跳检测
start(){
this.heartbeat = setTimeout(()=>{
this.data = {value:'开始心跳检测'}
this.send(JSON.stringify(this.data));
}, this.timeout)
}
// 重新连接
reconnect(){
clearInterval(this.heartbeat)
if(!this.isOpenSocket){
setTimeout(()=>{
this.connectSocketInit();
}, 3000)
}
}
}
2、在main.js中全局挂载
import WebsocketTask from './utils/websocket.js'
//自行修改请求地址
let websocket = new WebsocketTask('ws://xx.xx.xx.xx:xx/',5000)
// 挂载到全局
Vue.prototype.$websocket = websocket;
3、在组件中调用
<template>
<u-button @click="test" type="primary">测试websocket</u-button>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
test(){
let data = {value:'发送的消息'};
this.$websocket.send(JSON.stringify(data))
}
}
}
</script>
<style lang="scss" scoped>
</style>