websoket的简单使用

最近vue项目要做数据实时刷新,当用户用手机或者在后台取号结束,投屏需要做到实时刷新。

  • 首先我们在页面刚进去的时候开始长连接,页面销毁时关闭长连接
data(){
  return{
     websock: null,
     lockReconnect:false,    //避免重复连接,因为onerror之后会立即触发 onclose
     heartBeat:false,//心跳检测
  }
},
 created(){
        //页面刚进入时开启长连接
        this.initWebSocket()
 },
 destroyed: function() {
        //页面销毁时关闭长连接
   this.websock.close('4100')                   //离开路由之后断开websocket连接
      clearTimeout(this.heartBeat.timeoutObj);
      clearTimeout(this.heartBeat.serverTimeoutObj);
},
  • 初始化webskoket
initWebSocket(){
        let baseurl=this.accountinfo.base_ws_url
        let wsurl = baseurl+'/hos?app_key=' + this.app_id;
        this.websock = new WebSocket(wsurl);
        this.websock.onopen = this.websocketonopen;          //连接成功
        this.websock.onmessage = this.websocketonmessage;    //广播成功
        this.websock.onerror = this.websocketonerror;        //连接断开,失败
        this.websock.onclose = this.websocketclose;          //连接关闭
      },
  • 失败重连
websocketonerror(){
   console.log('连接失败')
   this.reconnect();
},  
websocketclose(event){
//如果是主动关闭,不再重连
  console.log('断开连接');
  if(event.code=='4100'){
    return;
  }
  this.reconnect();
},
reconnect(){
  var that = this;
    if(this.lockReconnect){//连接失败之后之后会相继触发 连接关闭,不然会连接上两个 WebSocket
            return
        }
        this.lockReconnect = true;
        setTimeout(()=>{ //没连接上会一直重连,设置延迟避免请求过多
           console.log('失败重连')
           that.msg="正在重连中"
            that.fail_box=true;
            that.initWebSocket();
            that.lockReconnect = false;
        },2000)
        },  
}
  • 心跳检测
created(){
        this.initWebSocket();
        var that = this;
        this.heartBeat = {
                timeout: 5000,//10s
                timeoutObj: null,
                serverTimeoutObj: null,
                heartStr:'1',
                reset: function(){
                    clearTimeout(this.timeoutObj);
                    clearTimeout(this.serverTimeoutObj);
                 this.start();
                },
                start: function(){
                    var self = this;
                    this.timeoutObj = setTimeout(function(){
                        that.websock.send(self.heartStr);
                        self.serverTimeoutObj = setTimeout(function(){
                            that.websock.close('4100');//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                        }, self.timeout)
                    }, this.timeout)
                },
            }
}
  • 连接成功,监测心跳检测
websocketonopen(){
   console.log('连接成功')
   this.heartBeat.start();
},

*监听返回的信息

websocketonmessage(data){
        this.heartBeat.reset();
        console.log(data.data)//返回的信息
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,142评论 1 32
  • 一:什么是闭包?闭包的用处? (1)闭包就是能够读取其他函数内部变量的函数。在本质上,闭包就 是将函数内部和函数外...
    xuguibin阅读 9,739评论 1 52
  • 或许又是一场成长中的冒险,或许睿会在多次反复和实践中学会自控吧?何况,他都拿保证书与我们叫板~~不买摆明了对他不信...
    子转阅读 249评论 0 0
  • “这一轮演示中,法德尔先从一个盒子中拿出了iPod要使用的各种元件,并把它们摆在了桌上,有1.8英寸的硬盘、液晶显...
    罗兰格咨询阅读 464评论 0 0
  • pragma mark 判断是否为空串 -(BOOL)isNull:(id)object{if ([object ...
    浅_若清风阅读 156评论 0 0