vue使用 封装websocket心跳包

这套代码可以拿过去直接用 一些注意我会在下面代码中加上注释:

谢谢支持

核心代码

 1 //这里需要引入vuex
 2 import store from './store';
 3 
 4 let wsConnection = {
 5   $ws: null,
 6   lockReturn: false,
 7   timeout: 60 * 1000 * 5,
 8   timeoutObj: null,
 9   timeoutNum: null,
10   serverTimeoutObj: null,
11   //初始化webSocket长连接
12   initWebSocket: function () {
13     let corpId = localStorage.getItem('corpId');
14     let name = localStorage.getItem('username');
15     this.$ws = new WebSocket(wsurl);//写入地址 这里的地址可以在initWebSocket方法加入参数
16     this.$ws.onopen = this.wsOpen;
17     this.$ws.onclose = this.wsClose;
18     this.$ws.onmessage = this.wsMsg;
19     this.$ws.onerror = this.wsError;
20   },
21   //打开websocket
22   wsOpen: function (e) {
23     //开始websocket心跳
24     wsConnection.startWsHeartbeat();
25     console.log('ws success')
26   },
27   wsClose: function (e) {
28     console.log(e, 'ws close')
29   },
30   wsMsg: function (msg) {
31     //每次接收到服务端消息后 重置websocket心跳
32     wsConnection.resetHeartbeat();
33     //服务端发送来的消息存到vuex
34     store.commit('web_socket_msg', msg)
35   },
36   wsError: function (err) {
37     console.log(err, 'ws error');
38     wsConnection.reconnect()
39   },
40   //重启websocket
41   reconnect: function () {
42     let _this = this;
43     if (_this.lockReturn) {
44       return;
45     }
46     _this.lockReturn = true;
47     _this.timeoutNum && clearTimeout(_this.timeoutNum);
48     _this.timeoutNum = setTimeout(function () {
49       _this.initWebSocket();
50       _this.lockReturn = false;
51     }, 3000);
52   },
53   startWsHeartbeat: function () {
54     let _this = this;
55     _this.timeoutObj && clearTimeout(_this.timeoutObj);
56     _this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj);
57     _this.timeoutObj = setInterval(function () {
58       //判断websocket当前状态
59       if (_this.$ws.readyState != 1) {
60         _this.reconnect()
61       }
62     }, _this.timeout);
63   },
64   //重置websocket心跳
65   resetHeartbeat: function () {
66     let _this = this;
67     clearTimeout(_this.timeoutObj);
68     clearTimeout(_this.serverTimeoutObj);
69     _this.startWsHeartbeat()
70   }
71 };
72 
73 //抛出websocket对象
74 export default wsConnection

websocket方法调用

 

 1 //在main.js引入
 2 import wsConnection from './vuex/wsStore'
 3 //挂载vue原型链
 4 Vue.prototype.$setWs = wsConnection;
 5 
 6 //在使用地方调用
 7  $this.$setWs.initWebSocket();
 8 
 9 //在需要使用服务端推送过来的消息时
10 //在computed方法声明
11 getWsMsg() {
12    //在核心代码接收到的服务端信息存储到vuex的属性
13     return this.$store.state.webSocketMsg
14 }
15 //在watch方法   监听  getWsMsg  
16  getWsMsg: function (data, val) {
17    console.log(data);
18    //.......
19 }      

此代码为本博主原创,转载请注明出处(支持原创! 谢谢~)

 

posted @ 2019-10-25 18:40  _阿雨  阅读(420)  评论(0编辑  收藏  举报