1 | 'use strict';
|
2 |
|
3 | var SockJS = require('sockjs-client/dist/sockjs');
|
4 |
|
5 | var retries = 0;
|
6 | var sock = null;
|
7 |
|
8 | var socket = function initSocket(url, handlers) {
|
9 | sock = new SockJS(url);
|
10 |
|
11 | sock.onopen = function onopen() {
|
12 | retries = 0;
|
13 | };
|
14 |
|
15 | sock.onclose = function onclose() {
|
16 | if (retries === 0) {
|
17 | handlers.close();
|
18 | }
|
19 |
|
20 |
|
21 | sock = null;
|
22 |
|
23 | if (retries <= 10) {
|
24 |
|
25 |
|
26 |
|
27 | var retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100;
|
28 | retries += 1;
|
29 | setTimeout(function () {
|
30 | socket(url, handlers);
|
31 | }, retryInMs);
|
32 | }
|
33 | };
|
34 |
|
35 | sock.onmessage = function onmessage(e) {
|
36 |
|
37 | var msg = JSON.parse(e.data);
|
38 |
|
39 | if (handlers[msg.type]) {
|
40 | handlers[msg.type](msg.data);
|
41 | }
|
42 | };
|
43 | };
|
44 |
|
45 | module.exports = socket; |
\ | No newline at end of file |