美文网首页
vue全局使用WebSocket

vue全局使用WebSocket

作者: 为光pig | 来源:发表于2020-12-08 15:41 被阅读0次

    vue接入websocket

    首先就是网上的写法有很多但是 都是需要创建一个对象进行相关的状态回调,有的是需要创建一个初始化方法进行相关的状态回调,然后看的我就一句话 都挺好的,反正就是需要你去创建对象接收发送消息,然后我就在这写一个全局的使用的,因为我觉得大部分就是作为消息推送来用所以全局来用蛮好的。

    websocket是什么:

    首先是是基于TCP的 全双工 通信的协议 然后就是websoket是通过客户端向服务器建立连接,保持客户端和服务器端双向的通信的过程。相互收发消息

    websocket的使用相关实例状态:

    1>readyState属性返回实例对象的当前状态。共四种:

    CONNECTING:值为0,表示正在连接。

    OPEN:值为1,表示连接成功,可以通信了。

    CLOSING:值为2,表示连接正在关闭。

    CLOSED:值为3,表示连接已经关闭,或者打开连接失败。

    2> onopen: 实例对象的onpen属性,用于指定连接成功后的回调函数。

    3>onclose: 实例对象的onclose属性,用于指定连接关闭后的回调函数。

    4>onmessage: 实例对象的onmessage属性,用于指定收到服务器 数据后的回调函数。

    5>send:实例对象的send()方法用于向服务器发送数据

    具体使用:

    1>首先创建一个全局文件: 在main.js 里面进行引入

    // global.js 文件
    export default {
        ws: {},
        setWs: function(newWs) {
            this.ws = newWs
        }
    }
    
    // main.js 文件
    import global from './xx/global.js'
    Vue.prototype.global = global
    

    2> 在APP.vue 里面进行初始化 (回调有多个状态 但是只写了连接成功和失败的方法)

    //app.vue
    oncerate(){
    //初始化方法
     this.localSocket
     
    }
    
    methods(){ 
    
                            //app.vue
                localSocket() {
                    let that = this;
                    if ("WebSocket" in window) {
                        // console.log("您的浏览器支持 WebSocket!");
                        // location.host
                        that.ws = new WebSocket("ws://"+ 'ceshidizhi');
                        that.global.setWs(that.ws);
                        that.ws.onopen = function () {
                            console.log('websocket连接成功');
                        };
    
                        that.ws.onclose = function () {
                            // 关闭 websocket
                            console.log("连接已关闭...");
                            //断线重新连接
                            setTimeout(() => {
                                that.localSocket();
                            }, 2000);
                        };
                    } else {
                        // 浏览器不支持 WebSocket
                        console.log("您的浏览器不支持 WebSocket!");
                        this.openNotificationWithIcon('error', '浏览器', '您的浏览器不支持显示消息请更换', 1,1)
                    }
                },
    
    }
    

    3>然后就可以在其他页面进行数据交互( 看代码就能看出来 使用全局的对象进行数据获取发送)

    //pageA.vue
    
    // 发送和接收消息
    handdleMsg(msg) {
      let that = this;
      console.log(that.global.ws);
      if (that.global.ws && that.global.ws.readyState == 1) {
        console.log("发送信息", msg);
        that.global.ws.send(msg);
      }
      that.global.ws.onmessage = function(res) {
        console.log("收到服务器内容", res);
      };
    }
    

    展示效果:我没有截图 就是连接成功后console里面会输出值的 跑起来看看就知道了

    注意:

    在使用的时候,初始化不一定要放在 APP.vue里面 就像我需要在登录成功之后拿到一个值,使用这个值去拼接地址,所以我就只能登录后在进行连接,我就省了个事情,直接放在了顶部的组件里面。

    长连接 在长时间不发送消息的时候,会自动断开。原因是运维那块使用了nginx服务,会配置一个时间段, 在这个时间里,如果一直灭有数据的传输,连接就会在这个时间之后自动关闭。因为我们无法控制用户什么时候去触发websocket消息的推送。所以下边

    心跳包机制:

    //在onopen开始之后直接进行f方法调用 数据数据发送
    start() {    // 发送心跳
          clearInterval(this.timeoutObj)
          this.timeoutObj = setInterval(() => {
            let that = this;
            let date = new Date()        
             if (that.global.ws && that.global.ws.readyState == 1) {
                console.log("发送信息", msg);
                that.global.ws.send(`发送心跳给后端${date}`);
            }
          }, 2 * 60 * 1000)
        }
    

    代码

    // 创建websocket连接
                createWebSocket(){
                    let that = this;
                    that.webSocet = null;
                    that.webSocet= new WebSocket(process.env.VUE_APP_SOCKET_URL);
                    // console.log('that.webSocet',that.webSocet);
                    if(that.webSocet.readyState == 0 && !that.timeoutnum){
                        that.timer = setInterval(() => {
                            if(that.timer_num < 3 && that.webSocet.readyState == 0 ){
                                that.timer_num++;
                            }else{
                                clearInterval(that.timer);
                                that.timer = null;
                                that.timer_num = 0;
                                // 只要不成功就连接
                                if(that.webSocet.readyState != 1){
                                    that.reconnect();
                                }
                            }
                        }, 1000);
                    }
                    //链接成功时
                    that.webSocet.onopen = function(){
                        //开启心跳
                        that.start(); 
                    }
                    //收到消息时
                    that.webSocet.onmessage = (msgInfo) => {
                        // console.log('接收到的消息',msgInfo);
                        that.UP_WEBSOCKETINFO({data:msgInfo.data,timer:msgInfo.timeStamp});
                        //收到服务器信息,心跳重置
                        that.reset();
                    }
                    //连接错误
                    that.webSocet.onerror = function(){
                        console.log("WebSocket连接发生错误");
                        //重连
                        that.reconnect();
                    };
                    // 监听组件的销毁
                    that.$once('hook:beforeDestroy', () => {
                         if(that.webSocet.close){
                            that.webSocet.close();
                            that.webSocet.onclose = () =>{ 
                                console.log('web socket 链接已关闭'); 
                            };
                        }
                    })
                },
                reconnect() {//重新连接
                    let that = this;
                    if(that.webSocet && that.webSocet.readyState == 1){
                        clearInterval(that.timeoutnum);
                        that.timeoutnum = null;
                        that.timeNum = 0;
                        return;
                    }
                    if(!that.timeoutnum) {
                        that.timeoutnum = setInterval(function () {
                            if(that.webSocet && that.webSocet.readyState == 1){
                                clearInterval(that.timeoutnum);
                                that.timeoutnum = null;
                                that.timeNum = 0;
                                return;
                            }   
                            //新连接
                            that.createWebSocket();
                            that.timeNum++;
                            if(that.timeNum >= 3){
                                clearInterval(that.timeoutnum);
                                that.timeoutnum = null;
                                that.timeNum = 0;
                            }
                        },1000);
                    };
                },
                reset(){//重置心跳
                    //清除时间
                    clearTimeout(this.timeoutObj);
                    clearTimeout(this.serverTimeoutObj);
                    //重启心跳
                    this.start();
                },
                start(){//开启心跳
                    let that = this;
                    that.timeoutObj && clearTimeout(that.timeoutObj);
                    that.serverTimeoutObj && clearTimeout(that.serverTimeoutObj);
                    that.timeoutObj = setTimeout(function(){
                        //这里发送一个心跳,后端收到后,返回一个心跳消息,
                        if (that.webSocet && that.webSocet.readyState == 1) {//如果连接正常
                            that.webSocet.send(
                                that.userInfo.userId + '-' + 
                                that.userInfo.userName + '-' +
                                that.userInfo.token
                            );
                        }else{//否则重连
                            that.reconnect();
                        }
                        
                    }, that.timeout)
                },
    
    ...mapMutations('userInfo',{
                    UP_WEBSOCKETINFO:'UP_WEBSOCKETINFO'
                })
    
    [websocket关于禁止一个账号多窗口链接的问题]

    通过websocket的session.getSessionId()与oldSession.getSessionId()来equals判断是否是新窗口。 如果不同不让链接。

    问题1.虽然新来的链接连不上,但是如果原窗口的链接断线重连也会认为是新socket,也会被禁止链接。

    解决方法: 原窗口链接时,原客户端窗口先发关闭请求, 然后再连即可连上。

    问题2. 如果上面原客户端窗口关闭请求服务端没有收到怎么办? (网络情况很复杂)

    可以在onError和onClose中获取到指定的oldSession,判断isOpen(), 如果为false则说明已为僵尸链接,移除它即可。

    相关文章

      网友评论

          本文标题:vue全局使用WebSocket

          本文链接:https://www.haomeiwen.com/subject/qgtqgktx.html