uniapp websocket单页面监听

本文介绍了如何在uni应用中封装WebSocket,实现WebSocket的连接、断开、消息接收以及存储管理,便于在单页面应用中进行消息监听和缓存同步。
摘要由CSDN通过智能技术生成

,封装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 = []
			}		
		},

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值