VUE-添加长链接webSocket,全局使用,接收消息并处理

App.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// App.vue
export default {
    data() {
        return {
            // socket参数
            socket: null,
            timeout: 10 * 1000, // 45秒一次心跳
            timeoutObj: null, // 心跳心跳倒计时
            serverTimeoutObj: null, // 心跳倒计时
            timeoutnum: null, // 断开 重连倒计时
            lockReconnect: false, // 防止
            websocket: null
        };
    },
    mounted() {
        this.initWebSocket(userId); // userId为socket链接的参数
    },
    methods:{
        initWebSocket(supplierId) {
            // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
            let wsUrl = `wss://192.168.1.33/rest/supplier-api/wss/websocket/${userId}`;
            this.websocket = new WebSocket(wsUrl);
            this.websocket.onopen = this.websocketonopen;
            this.websocket.onerror = this.websocketonerror;
            this.websocket.onmessage = this.setOnmessageMessage;
            this.websocket.onclose = this.websocketclose;
            // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
            // window.onbeforeunload = that.onbeforeunload
        },
        start() {
            console.log('start');
            //清除延时器
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(() => {
                if (this.websocket && this.websocket.readyState == 1) {
                    this.websocket.send('heartBath');//发送消息,服务端返回信息,即表示连接良好,可以在socket的onmessage事件重置心跳机制函数
                } else {
                    this.reconnect();
                }
                //定义一个延时器等待服务器响应,若超时,则关闭连接,重新请求server建立socket连接
                this.serverTimeoutObj = setTimeout(() => {
                    this.websocket.close();
                }, this.timeout)
            }, this.timeout)
        },
        reset() { // 重置心跳
            // 清除时间
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            // 重启心跳
            this.start();
        },
        // 重新连接
        reconnect() {
            if (this.lockReconnect) return
            this.lockReconnect = true;
            //没连接上会一直重连,设置延迟避免请求过多
            this.timeoutnum && clearTimeout(this.timeoutnum);
            this.timeoutnum = setTimeout(() => {
                this.initWebSocket();
                this.lockReconnect = false;
            }, 5000)
        },
        async setOnmessageMessage(event) {
            console.log(event.data, '获得消息');
            this.reset();
            // 自定义全局监听事件
            window.dispatchEvent(new CustomEvent('onmessageWS', {
                detail: {
                    data: event.data
                }
            }))
            // //发现消息进入    开始处理前端触发逻辑
            // if (event.data === 'success' || event.data === 'heartBath') return
        },
        websocketonopen() {
            //开启心跳
            this.start();
            console.log("WebSocket连接成功!!!"+new Date()+"----"+this.websocket.readyState);
        },
        websocketonerror(e) {               
            console.log("WebSocket连接发生错误" + e);             
        },
        websocketclose(e) {
            this.websocket.close();
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            console.log("WebSocket连接关闭");
        },
        websocketsend(messsage) {
            that.websocket.send(messsage)
        },
        closeWebSocket() { // 关闭websocket
            that.websocket.close()
        },
    }

  

  

在使用页面上调用,举例index.vue 
1
2
3
4
5
6
7
8
9
10
11
mounted () {
    // 添加socket通知监听
    window.addEventListener('onmessageWS', this.getSocketData)
},
methods: {
    // 收到消息处理
    getSocketData (res) {
        //res.detail.data 就是你接收到的消息
        // ...业务处理
    },
}



 


以上是我参考他人的方法(我测试的时候是不能正常使用的)https://blog.csdn.net/MICHAEL_PRINCE/article/details/124492223
以下是我根据我自己的项目做的调整
APP.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
initWebSocket(supplierId) {
                // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
                let wsUrl = `wss://XXXXXXXX`;
                this.websocket = new WebSocket(wsUrl);
                this.websocket.onopen = this.websocketonopen;
                this.websocket.onerror = this.websocketonerror;
                this.websocket.onmessage = this.setOnmessageMessage;
                this.websocket.onclose = this.websocketclose;
                // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
                // window.onbeforeunload = that.onbeforeunload
            },
            start() {
                console.log('start');
                let that=this;
                //清除延时器
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                // this.timeoutObj = setTimeout(() => {
                    console.log("this.websocket :",this.websocket )
                    if (that.websocket && that.websocket.readyState == 1) {
                        console.log("进入发送心跳包")
                        that.websocket.send('{"token":"' + cookie.get("token") + '"}'); //发送消息,服务端返回信息,即表示连接良好,可以在socket的onmessage事件重置心跳机制函数
                    } else {
                        console.log("心跳包失败,重新链接")
                        that.reconnect();
                    }
                    //定义一个延时器等待服务器响应,若超时,则关闭连接,重新请求server建立socket连接
                    // this.serverTimeoutObj = setTimeout(() => {
                    //  this.websocket.close();
                    // }, this.timeout)
                // }, this.timeout)
            },
            reset() { // 重置心跳
                // 清除时间
                clearTimeout(this.timeoutObj);
                clearTimeout(this.serverTimeoutObj);
                // 重启心跳
                this.start();
            },
            // 重新连接
            reconnect() {
                if (this.lockReconnect) return
                this.lockReconnect = true;
                //没连接上会一直重连,设置延迟避免请求过多
                this.timeoutnum && clearTimeout(this.timeoutnum);
                this.timeoutnum = setTimeout(() => {
                    this.initWebSocket();
                    this.lockReconnect = false;
                }, this.timeout)
            },
            async setOnmessageMessage(event) {
                console.log(event.data, '获得消息');
                this.reset();
                // 自定义全局监听事件
                window.dispatchEvent(new CustomEvent('onmessageWS', {
                    detail: {
                        data: event.data
                    }
                }))
                // //发现消息进入    开始处理前端触发逻辑
                // if (event.data === 'success' || event.data === 'heartBath') return
            },
            websocketonopen() {
                //开启心跳
                let that=this;
                let timer;
                timer = setInterval(function (){
                    that.start();
                },that.timeout)
                // this.start();   //因为我这边一直报心跳延时,所以我添加了setInterval来发送心跳
                console.log("WebSocket连接成功!!!" + new Date() + "///////////" + this.websocket.readyState);
            },
            websocketonerror(e) {
                console.log("WebSocket连接发生错误" + e);
            },
            websocketclose(e) {
                this.websocket.close();
                clearTimeout(this.timeoutObj);
                clearTimeout(this.serverTimeoutObj);
                console.log("WebSocket连接关闭");
            },
            websocketsend(messsage) {
                that.websocket.send(messsage)
            },
            closeWebSocket() { // 关闭websocket
                that.websocket.close()
            },

  










posted @   MiniDuck  阅读(1952)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示