forked from webpack/webpack-dev-server
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsocket.js
42 lines (32 loc) · 1.04 KB
/
socket.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
'use strict';
const SockJS = require('sockjs-client/dist/sockjs');
let retries = 0;
let sock = null;
const socket = function initSocket(url, handlers) {
sock = new SockJS(url);
sock.onopen = function onopen() {
retries = 0;
};
sock.onclose = function onclose() {
if (retries === 0) { handlers.close(); }
// Try to reconnect.
sock = null;
// After 10 retries stop trying, to prevent logspam.
if (retries <= 10) {
// Exponentially increase timeout to reconnect.
// Respectfully copied from the package `got`.
// eslint-disable-next-line no-mixed-operators, no-restricted-properties
const retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
retries += 1;
setTimeout(() => {
socket(url, handlers);
}, retryInMs);
}
};
sock.onmessage = function onmessage(e) {
// This assumes that all data sent via the websocket is JSON.
const msg = JSON.parse(e.data);
if (handlers[msg.type]) { handlers[msg.type](msg.data); }
};
};
module.exports = socket;