-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck.js
More file actions
89 lines (63 loc) · 2.2 KB
/
check.js
File metadata and controls
89 lines (63 loc) · 2.2 KB
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
const WebSockets = require('ws')
class WS extends WebSockets {
constructor(...args) {
super(...args)
this.___activityTimeout = false
this.___pongTimeout = false
this.___activityTimer = null
this.___pongTimer = null
this.___checking = false
this.___killer = false
}
get checking() { return this.___checking }
set checking(bool) {
if (typeof bool != 'boolean') throw 'checking argument must be boolean: ' + bool
return this.___checking = bool
}
check = (activityTimeout, pongTimeout, killer) => {
if (!activityTimeout || !pongTimeout) throw new Error('missing arguments')
this.checking = true
this.___activityTimeout = activityTimeout
this.___pongTimeout = pongTimeout
if (killer) this.___killer = true
let dis = this
this.prependListener('message', dis.___refresh)
this.prependListener('pong', dis.___refresh)
if (killer) this.on('lost', this.___onLost)
this.once('open', function () {
dis.___activityTimer = setTimeout(dis.___timed, dis.___activityTimeout)
dis.prependListener('open', dis.___refresh)
})
}
stopChecking = () => {
this.checking = false
let dis = this
this.removeListener('message', dis.___refresh)
this.removeListener('open', dis.___refresh)
this.removeListener('pong', dis.___refresh)
clearTimeout(dis.___activityTimer)
clearTimeout(dis.___pongTimer)
}
___refresh = () => {
if (!this.___activityTimer) throw 'check activity error: no timer set'
return this.___activityTimer.refresh()
}
___timed = () => {
if (this.readyState !== 1) return this.emit('lost')
this.emit('knock')
let dis = this
this.___pongTimer = setTimeout(function () {
dis.emit('lost')
dis.removeListener('pong', dis.___pong)
}, dis.___pongTimeout)
this.prependOnceListener('pong', dis.___pong)
this.ping()
}
___pong = () => {
clearTimeout(this.___pongTimer)
}
___onLost = () => {
this.terminate()
}
}
module.exports = WS