我是靠谱客的博主 震动奇迹,这篇文章主要介绍vue使用 封装websocket心跳包,现在分享给大家,希望可以做个参考。

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

复制代码
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
//这里需要引入vuex import store from './store'; let wsConnection = { $ws: null, lockReturn: false, timeout: 60 * 1000 * 5, timeoutObj: null, timeoutNum: null, serverTimeoutObj: null, //初始化webSocket长连接 initWebSocket: function () { this.$ws = new WebSocket(wsurl);//写入地址 这里的地址可以在initWebSocket方法加入参数 this.$ws.onopen = this.wsOpen; this.$ws.onclose = this.wsClose; this.$ws.onmessage = this.wsMsg; this.$ws.onerror = this.wsError; }, //打开websocket wsOpen: function (e) { //开始websocket心跳 wsConnection.startWsHeartbeat(); console.log('ws success') }, wsClose: function (e) { console.log(e, 'ws close') }, wsMsg: function (msg) { //每次接收到服务端消息后 重置websocket心跳 wsConnection.resetHeartbeat(); //服务端发送来的消息存到vuex store.commit('web_socket_msg', msg) }, wsError: function (err) { console.log(err, 'ws error'); wsConnection.reconnect() }, //重启websocket reconnect: function () { let _this = this; if (_this.lockReturn) { return; } _this.lockReturn = true; _this.timeoutNum && clearTimeout(_this.timeoutNum); _this.timeoutNum = setTimeout(function () { _this.initWebSocket(); _this.lockReturn = false; }, 3000); }, startWsHeartbeat: function () { let _this = this; _this.timeoutObj && clearTimeout(_this.timeoutObj); _this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj); _this.timeoutObj = setInterval(function () { //判断websocket当前状态 if (_this.$ws.readyState != 1) { _this.reconnect() } }, _this.timeout); }, //重置websocket心跳 resetHeartbeat: function () { let _this = this; clearTimeout(_this.timeoutObj); clearTimeout(_this.serverTimeoutObj); _this.startWsHeartbeat() } }; //抛出websocket对象 export default wsConnection

websocket方法调用

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

=end=

最后

以上就是震动奇迹最近收集整理的关于vue使用 封装websocket心跳包的全部内容,更多相关vue使用内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(99)

评论列表共有 0 条评论

立即
投稿
返回
顶部