1 | ;
|
2 | /* global __webpack_dev_server_client__ */
|
3 |
|
4 | /* eslint-disable
|
5 | camelcase
|
6 | */
|
7 | // this SockJSClient is here as a default fallback, in case inline mode
|
8 | // is off or the client is not injected. This will be switched to
|
9 | // WebsocketClient when it becomes the default
|
10 | // important: the path to SockJSClient here is made to work in the 'client'
|
11 | // directory, but is updated via the webpack compilation when compiled from
|
12 | // the 'client-src' directory
|
13 |
|
14 | var Client = typeof __webpack_dev_server_client__ !== 'undefined' ? __webpack_dev_server_client__ : // eslint-disable-next-line import/no-unresolved
|
15 | require('./clients/SockJSClient');
|
16 | var retries = 0;
|
17 | var client = null;
|
18 |
|
19 | var socket = function initSocket(url, handlers) {
|
20 | client = new Client(url);
|
21 | client.onOpen(function () {
|
22 | retries = 0;
|
23 | });
|
24 | client.onClose(function () {
|
25 | if (retries === 0) {
|
26 | handlers.close();
|
27 | } // Try to reconnect.
|
28 |
|
29 |
|
30 | client = null; // After 10 retries stop trying, to prevent logspam.
|
31 |
|
32 | if (retries <= 10) {
|
33 | // Exponentially increase timeout to reconnect.
|
34 | // Respectfully copied from the package `got`.
|
35 | // eslint-disable-next-line no-mixed-operators, no-restricted-properties
|
36 | var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
|
37 | retries += 1;
|
38 | setTimeout(function () {
|
39 | socket(url, handlers);
|
40 | }, retryInMs);
|
41 | }
|
42 | });
|
43 | client.onMessage(function (data) {
|
44 | var msg = JSON.parse(data);
|
45 |
|
46 | if (handlers[msg.type]) {
|
47 | handlers[msg.type](msg.data);
|
48 | }
|
49 | });
|
50 | };
|
51 |
|
52 | module.exports = socket; |
\ | No newline at end of file |