我是靠谱客的博主 愤怒灰狼,这篇文章主要介绍websocket 心跳包(此方法也是借鉴网上,并非原创但实测没问题),现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
data() { return { ws: null, //建立的连接 lockReconnect: false, //是否真正建立连接 timeout: 60 * 1000, //60秒一次心跳 timeoutObj: null, //心跳心跳倒计时 serverTimeoutObj: null, //心跳倒计时 timeoutnum: null, //断开 重连倒计时 } }
复制代码
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
methods:{ // 连接ws initWebpack() { let token = this.$store.state.mUinfo.id let wsurl = ''; //ws地址,这里加入自己的地址即可 wsurl = 'ws://' + xxxxx + 'api/v1/users/notices/ws' this.ws = new WebSocket(wsurl, [token]); this.ws.onopen = this.onopen; this.ws.onmessage = this.onmessage; this.ws.onclose = this.onclose; this.ws.onerror = this.onerror; }, reconnect() { //重新连接 var that = this; if (that.lockReconnect) { return; }; that.lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 that.timeoutnum && clearTimeout(that.timeoutnum); that.timeoutnum = setTimeout(function () { //新连接 that.initWebpack(); that.lockReconnect = false; }, 5000); }, reset() { //重置心跳 var that = this; //清除时间 clearTimeout(that.timeoutObj); clearTimeout(that.serverTimeoutObj); //重启心跳 that.start(); }, start() { //开启心跳 console.log('开启心跳'); var self = this; self.timeoutObj && clearTimeout(self.timeoutObj); self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj); self.timeoutObj = setTimeout(function () { //这里发送一个心跳,后端收到后,返回一个心跳消息, if (self.ws.readyState == 1) { //如果连接正常 self.ws.send("heartCheck"); //这里可以自己跟后端约定 } else { //否则重连 self.reconnect(); } self.serverTimeoutObj = setTimeout(function () { //超时关闭 self.ws.close(); }, self.timeout); }, self.timeout) }, onopen() { console.log("open"); //开启心跳 this.start(); }, onmessage(e) { let data = JSON.parse(e.data); // console.log('接收消息', data); //收到服务器信息,心跳重置 this.reset(); }, onclose(e) { console.log("连接关闭"); console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean); //重连 this.reconnect(); }, onerror(e) { console.log("出现错误"); //重连 this.reconnect(); }, onsend(msg) { //向服务器发送信息 //数据发送 this.websock.send(msg); }, }

最后

以上就是愤怒灰狼最近收集整理的关于websocket 心跳包(此方法也是借鉴网上,并非原创但实测没问题)的全部内容,更多相关websocket内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部