vue中使用WebSocket

 需要实现:有人触发门禁,就弹出消息信息

使用WebSocket 实现(由于项目重新发布会导致WebSocket断开连接,所以当断开时会定时请求连接WebSocket)

     websocketInfo(){
           var that = this;
           var min = 100;
           var max = 999;
           var range = max-min;
           var rande = Math.random();
           var num = min + Math.round(range*rande); 
                if(typeof(WebSocket) == "undefined") {
                console.log('您的浏览器不支持websocket');
                }else{
                    that.socket = new WebSocket(that.wsUrl+new Date().getTime()+num);
                    console.log('连接状态:~~~'+that.socket.readyState);	

                    //打开事件
                     if(that.timer.t10){
                             clearInterval(that.timer.t10);
                        }
                        if(that.timer.t11){
                             clearInterval(that.timer.t11);
                        }
                    that.socket.onopen = function() {
                        console.log("Socket 已打开");
                    };
                    //获得消息事件
                    that.socket.onmessage = function(msg) {
                        console.log(msg.data);
                        that.isstangerdetail = JSON.parse(msg.data);
                        if(that.isstangerdetail){
                            that.messageFlag?'':that.visitorDialog();
                        }
                        //发现消息进入开始处理前端触发逻辑
                    };
                    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
                    that.socket.onbeforeunload = function(err) {
                        that.websocket.close();
                    };
                    //关闭事件
                    that.socket.onclose = function(err) {
                        console.log('关闭');
                        console.log(err);
                         that.timer.t10 = setInterval(() =>{
                             clearInterval(that.timer.t11);
                            that.websocketInfo();
                         },3*1000)
                    };
                    //发生了错误事件
                    that.socket.onerror = function(err) {
                        console.log('错误');
                        console.log(err);
                         that.timer.t11 = setInterval(() =>{
                             clearInterval(that.timer.t10);
                            that.websocketInfo();
                         },3*1000)
                        //此时可以尝试刷新 页面
                    };
                
                }
       },

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值