,封装websocket
// 创建 websocket.js文件
export default class WebsocketTask{
constructor(url,time){
this.url = url
this.data = null
this.isOpenSocket = false
// 心跳检测
this.timeout = time
this.heartbeat = null
this.isClosePage = false
try{
return this.connectSocketInit()
}catch(e){
this.isOpenSocket = false
this.reconnect();
}
}
connectSocketInit(){
this.socketTask = uni.connectSocket({
url: this.url,
success: (data) => {
console.log(data,'88888888888888');
}
})
this.socketTask.onOpen((res)=>{
clearTimeout(this.heartbeat);
this.isOpenSocket = true
this.start();
})
this.socketTask.onClose(()=>{
console.log('关闭');
this.isOpenSocket = false;
if(this.isClosePage == false){
// this.reconnect();
}
})
}
getMessage(callback){
this.socketTask.onMessage((res)=>{
//接收消息
console.log(res,'message');
return callback(res)
})
}
close(){
this.socketTask.close(()=>{
clearInterval(this.heartbeat)
this.isClosePage = true
})
}
//发送消息
send(data){
this.socketTask.send({
data,
})
}
//开启心跳检测
start(){
this.heartbeat = setTimeout(()=>{
this.data = {value:'xx'}
this.send(JSON.stringify(this.data));
}, this.timeout)
}
// 重新连接
reconnect(){
console.log('重新链接');
clearInterval(this.heartbeat)
if(!this.isOpenSocket && !this.isClosePage){
setTimeout(()=>{
this.connectSocketInit();
}, 3000)
}
}
}
最开始是把接受消息放到init函数里面,发现这样监听的话很麻烦,不如直接外部接受消息
单页面调用
单页面调用比较简单,直接在mounted这个组件生命周期里面进行连接,然后开始监听消息,callback回调函数会在每次接受到消息的时候执行,不论你是否处在当前页面。
由于需要存储用户的消息,所以需要将接受到的消息存到缓存中,在onShow生命周期中赋给展示的List
//引入websocket文件
import WebsocketTask from '@/common/websocket'
mounted() {
this.webSocket = new WebsocketTask('ws://xxx/' + this.userInfo.id, 5000)
this.watchSocket();
},
watchSocket() {
this.webSocket.getMessage(opt => {
console.log("消息接收:", opt);
let message = JSON.parse(opt.data)
if(message.type == 3){
this.favorMessageList.unshift(message)
uni.setStorageSync('likeInfo',JSON.stringify(this.favorMessageList))
}else if(message.type == 2){
this.commentMessageList.unshift(message)
uni.setStorageSync('commentInfo',JSON.stringify(this.commentMessageList))
}
onShow() {
this.setMessage()
},
setMessage(){
if(uni.getStorageSync('likeInfo')){
this.favorMessageList = JSON.parse(uni.getStorageSync('likeInfo'))
}else{
this.favorMessageList = []
}
if(uni.getStorageSync('commentInfo')){
this.commentMessageList = JSON.parse(uni.getStorageSync('commentInfo'))
}else{
this.commentMessageList = []
}
},