我是靠谱客的博主 哭泣白云,这篇文章主要介绍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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var websocket = null; var lockReconnect = false; /** * 初始化websocket连接 */ function initWebSocket() { webSocketInit(); } /** * 连接ws */ function webSocketInit(){ try{ if('WebSocket' in window) { websocket = new WebSocket(url); //url为websocket地址 } else { alert("该浏览器不支持websocket!"); } }catch (e){ websocketReconnect(); //尝试重连websocket } websocket.onopen = function(event) { console.log("建立连接"); } websocket.onclose = function(event) { console.log('连接关闭') lockReconnect = false; websocketReconnect(); //尝试重连websocket } //建立通信后,监听到后端的数据传递过来了 websocket.onmessage = function(event) { heartCheck.start(); } websocket.onerror = function() { //alert('websocket通信发生错误!'); } window.onbeforeunload = function() { websocket.close(); } } /** * 重连ws */ function websocketReconnect(){ if (lockReconnect) { // 是否已经执行重连 return; }; lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 tt && clearTimeout(tt); var tt = setTimeout(function () { webSocketInit(); lockReconnect = false; console.log("正在重连"); heartCheck.start(); }, 5000) } //心跳检测 var heartCheck = { timeout: 120000, timeoutObj: null, serverTimeoutObj: null, start: function () { console.log('start'); var self = this; this.timeoutObj && clearTimeout(this.timeoutObj); this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj); this.timeoutObj = setTimeout(function () { //发送测试信息,后端收到后,返回一个消息, websocket.send('hello'); self.serverTimeoutObj = setTimeout(function () { //websocket.close(); }, self.timeout); }, this.timeout) } } /** * 发送ws消息 */ function sendWsMsgTimer(){ console.log("发送消息"); connectTimer = window.setInterval(function(){ websocket.send('hello'); },120000); }

最后

以上就是哭泣白云最近收集整理的关于websocket连接及心跳检测的全部内容,更多相关websocket连接及心跳检测内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部