-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathrobust-websocket.js
244 lines (210 loc) · 7.2 KB
/
robust-websocket.js
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
(function(factory, global) {
if (typeof define === 'function' && define.amd) {
define(function() {
return factory(global, navigator)
})
} else if (typeof exports === 'object' && typeof module === 'object') {
module.exports = factory(global, navigator)
} else {
// mock the navigator object when under test since `navigator.onLine` is read only
global.RobustWebSocket = factory(global, typeof Mocha !== 'undefined' ? Mocha : navigator)
}
})(function(global, navigator) {
var RobustWebSocket = function(url, protocols, userOptions) {
var realWs = { close: function() {} },
connectTimeout,
self = this,
attempts = 0,
reconnects = -1,
reconnectWhenOnlineAgain = false,
explicitlyClosed = false,
pendingReconnect,
opts = Object.assign({},
RobustWebSocket.defaultOptions,
typeof userOptions === 'function' ? { shouldReconnect: userOptions } : userOptions
)
if (typeof opts.timeout !== 'number') {
throw new Error('timeout must be the number of milliseconds to timeout a connection attempt')
}
if (typeof opts.shouldReconnect !== 'function') {
throw new Error('shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.')
}
['bufferedAmount', 'url', 'readyState', 'protocol', 'extensions'].forEach(function(readOnlyProp) {
Object.defineProperty(self, readOnlyProp, {
get: function() { return realWs[readOnlyProp] }
})
})
function clearPendingReconnectIfNeeded() {
if (pendingReconnect) {
clearTimeout(pendingReconnect)
pendingReconnect = null
}
}
var ononline = function(event) {
if (reconnectWhenOnlineAgain) {
clearPendingReconnectIfNeeded()
reconnect(event)
}
},
onoffline = function() {
reconnectWhenOnlineAgain = true
realWs.close(1000)
},
connectivityEventsAttached = false
function detachConnectivityEvents() {
if (connectivityEventsAttached) {
global.removeEventListener('online', ononline)
global.removeEventListener('offline', onoffline)
connectivityEventsAttached = false
}
}
function attachConnectivityEvents() {
if (!connectivityEventsAttached) {
global.addEventListener('online', ononline)
global.addEventListener('offline', onoffline)
connectivityEventsAttached = true
}
}
self.send = function() {
return realWs.send.apply(realWs, arguments)
}
self.close = function(code, reason) {
if (typeof code !== 'number') {
reason = code
code = 1000
}
clearPendingReconnectIfNeeded()
reconnectWhenOnlineAgain = false
explicitlyClosed = true
detachConnectivityEvents()
return realWs.close(code, reason)
}
self.open = function() {
if (realWs.readyState !== WebSocket.OPEN && realWs.readyState !== WebSocket.CONNECTING) {
clearPendingReconnectIfNeeded()
reconnectWhenOnlineAgain = false
explicitlyClosed = false
newWebSocket()
}
}
function reconnect(event) {
if ((!opts.shouldReconnect.handle1000 && event.code === 1000) || explicitlyClosed) {
attempts = 0
return
}
if (navigator.onLine === false) {
reconnectWhenOnlineAgain = true
return
}
var delay = opts.shouldReconnect(event, self)
if (typeof delay === 'number') {
pendingReconnect = setTimeout(newWebSocket, delay)
}
}
Object.defineProperty(self, 'listeners', {
value: {
open: [function(event) {
if (connectTimeout) {
clearTimeout(connectTimeout)
connectTimeout = null
}
event.reconnects = ++reconnects
event.attempts = attempts
attempts = 0
reconnectWhenOnlineAgain = false
}],
close: [reconnect]
}
})
Object.defineProperty(self, 'attempts', {
get: function() { return attempts },
enumerable: true
})
Object.defineProperty(self, 'reconnects', {
get: function() { return reconnects },
enumerable: true
})
function newWebSocket() {
var newUrl = (typeof url === 'function' ? url(self) : url);
pendingReconnect = null
realWs = new WebSocket(newUrl, protocols || undefined)
realWs.binaryType = self.binaryType
attempts++
self.dispatchEvent(Object.assign(new CustomEvent('connecting'), {
attempts: attempts,
reconnects: reconnects
}))
connectTimeout = setTimeout(function() {
connectTimeout = null
detachConnectivityEvents()
self.dispatchEvent(Object.assign(new CustomEvent('timeout'), {
attempts: attempts,
reconnects: reconnects
}))
}, opts.timeout)
;['open', 'close', 'message', 'error'].forEach(function(stdEvent) {
realWs.addEventListener(stdEvent, function(event) {
self.dispatchEvent(event)
var cb = self['on' + stdEvent]
if (typeof cb === 'function') {
return cb.apply(self, arguments)
}
})
})
if (!opts.ignoreConnectivityEvents) {
attachConnectivityEvents()
}
}
if (opts.automaticOpen) {
newWebSocket()
}
}
RobustWebSocket.defaultOptions = {
// the time to wait before a successful connection
// before the attempt is considered to have timed out
timeout: 4000,
// Given a CloseEvent or OnlineEvent and the RobustWebSocket state,
// should a reconnect be attempted? Return the number of milliseconds to wait
// to reconnect (or null or undefined to not), rather than true or false
shouldReconnect: function(event, ws) {
if (event.code === 1008 || event.code === 1011) return
return [0, 3000, 10000][ws.attempts]
},
// Flag to control whether attachement to navigator online/offline events
// should be disabled.
ignoreConnectivityEvents: false,
// Create and connect the WebSocket when the instance is instantiated.
// Defaults to true to match standard WebSocket behavior
automaticOpen: true
}
RobustWebSocket.prototype.binaryType = 'blob'
// Taken from MDN https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
RobustWebSocket.prototype.addEventListener = function(type, callback) {
if (!(type in this.listeners)) {
this.listeners[type] = []
}
this.listeners[type].push(callback)
}
RobustWebSocket.prototype.removeEventListener = function(type, callback) {
if (!(type in this.listeners)) {
return
}
var stack = this.listeners[type]
for (var i = 0, l = stack.length; i < l; i++) {
if (stack[i] === callback) {
stack.splice(i, 1)
return
}
}
}
RobustWebSocket.prototype.dispatchEvent = function(event) {
if (!(event.type in this.listeners)) {
return
}
var stack = this.listeners[event.type]
for (var i = 0, l = stack.length; i < l; i++) {
stack[i].call(this, event)
}
}
return RobustWebSocket
}, typeof window != 'undefined' ? window : (typeof global != 'undefined' ? global : this));