1 | var RECONNECT_TIMEOUT, ReconnectingWebSocket,
|
2 | __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
|
3 |
|
4 | RECONNECT_TIMEOUT = 3 * 1000;
|
5 |
|
6 | ReconnectingWebSocket = (function() {
|
7 | function ReconnectingWebSocket(url, reconnectTimeout) {
|
8 | this.url = url;
|
9 | this.connect = __bind(this.connect, this);
|
10 | this.forceclose = false;
|
11 | this.reconnectTimeout = reconnectTimeout || RECONNECT_TIMEOUT;
|
12 | this.readyState = WebSocket.CONNECTING;
|
13 | this.connectionCount = 0;
|
14 | this.connect();
|
15 | }
|
16 |
|
17 | ReconnectingWebSocket.prototype.connect = function() {
|
18 | this.ws = new WebSocket(this.url);
|
19 | this.ws.onopen = (function(_this) {
|
20 | return function(event) {
|
21 | _this.readyState = WebSocket.OPEN;
|
22 | if (_this.connectionCount++) {
|
23 | return _this.onreconnect(event);
|
24 | } else {
|
25 | return _this.onopen(event);
|
26 | }
|
27 | };
|
28 | })(this);
|
29 | this.ws.onclose = (function(_this) {
|
30 | return function(event) {
|
31 | if (_this.forceclose) {
|
32 | _this.readyState = WebSocket.CLOSED;
|
33 | return _this.onclose(event);
|
34 | } else {
|
35 | _this.readyState = WebSocket.CONNECTING;
|
36 | return setTimeout(_this.connect, _this.reconnectTimeout);
|
37 | }
|
38 | };
|
39 | })(this);
|
40 | this.ws.onmessage = (function(_this) {
|
41 | return function(event) {
|
42 | return _this.onmessage(event);
|
43 | };
|
44 | })(this);
|
45 | return this.ws.onerror = (function(_this) {
|
46 | return function(event) {
|
47 | return _this.onerror(event);
|
48 | };
|
49 | })(this);
|
50 | };
|
51 |
|
52 | ReconnectingWebSocket.prototype.send = function(data) {
|
53 | try {
|
54 | return this.ws.send(data);
|
55 | } catch (_error) {
|
56 | return this.connect();
|
57 | }
|
58 | };
|
59 |
|
60 | ReconnectingWebSocket.prototype.close = function() {
|
61 | this.forceclose = true;
|
62 | return this.ws.close();
|
63 | };
|
64 |
|
65 | ReconnectingWebSocket.prototype.onopen = function(event) {};
|
66 |
|
67 | ReconnectingWebSocket.prototype.onclose = function(event) {};
|
68 |
|
69 | ReconnectingWebSocket.prototype.onreconnect = function(event) {};
|
70 |
|
71 | ReconnectingWebSocket.prototype.onmessage = function(event) {};
|
72 |
|
73 | ReconnectingWebSocket.prototype.onerror = function(event) {};
|
74 |
|
75 | ReconnectingWebSocket.prototype.onsend = function(event) {};
|
76 |
|
77 | return ReconnectingWebSocket;
|
78 |
|
79 | })();
|
80 |
|
81 | module.exports = ReconnectingWebSocket;
|