forked from daviddoran/typescript-reconnecting-websocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreconnecting-websocket.ts
188 lines (169 loc) · 6.26 KB
/
reconnecting-websocket.ts
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
// MIT License:
//
// Copyright (c) 2010-2012, Joe Walnes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/**
* This behaves like a WebSocket in every way, except if it fails to connect,
* or it gets disconnected, it will repeatedly poll until it succesfully connects
* again.
*
* It is API compatible, so when you have:
* ws = new WebSocket('ws://....');
* you can replace with:
* ws = new ReconnectingWebSocket('ws://....');
*
* The event stream will typically look like:
* onconnecting
* onopen
* onmessage
* onmessage
* onclose // lost connection
* onconnecting
* onopen // sometime later...
* onmessage
* onmessage
* etc...
*
* It is API compatible with the standard WebSocket API.
*
* Latest version: https://github.com/joewalnes/reconnecting-websocket/
* - Joe Walnes
*
* Latest TypeScript version: https://github.com/daviddoran/typescript-reconnecting-websocket/
* - David Doran
*/
class ReconnectingWebSocket {
//These can be altered by calling code
public debug:boolean = false;
//Time to wait before attempting reconnect (after close)
public reconnectInterval:number = 1000;
//Time to wait for WebSocket to open (before aborting and retrying)
public timeoutInterval:number = 2000;
//Should only be used to read WebSocket readyState
public readyState:number;
//Whether WebSocket was forced to close by this client
private forcedClose:boolean = false;
//Whether WebSocket opening timed out
private timedOut:boolean = false;
//List of WebSocket sub-protocols
private protocols:string[] = [];
//The underlying WebSocket
private ws:WebSocket;
private url:string;
/**
* Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
*/
public static debugAll = false;
//Set up the default 'noop' event handlers
public onopen:(ev:Event) => void = function (event:Event) {};
public onclose:(ev:CloseEvent) => void = function (event:CloseEvent) {};
public onconnecting:() => void = function () {};
public onmessage:(ev:MessageEvent) => void = function (event:MessageEvent) {};
public onerror:(ev:ErrorEvent) => void = function (event:ErrorEvent) {};
constructor(url:string, protocols:string[] = []) {
this.url = url;
this.protocols = protocols;
this.readyState = WebSocket.CONNECTING;
this.connect(false);
}
public connect(reconnectAttempt:boolean) {
this.ws = new WebSocket(this.url, this.protocols);
this.onconnecting();
this.log('ReconnectingWebSocket', 'attempt-connect', this.url);
var localWs = this.ws;
var timeout = setTimeout(() => {
this.log('ReconnectingWebSocket', 'connection-timeout', this.url);
this.timedOut = true;
localWs.close();
this.timedOut = false;
}, this.timeoutInterval);
this.ws.onopen = (event:Event) => {
clearTimeout(timeout);
this.log('ReconnectingWebSocket', 'onopen', this.url);
this.readyState = WebSocket.OPEN;
reconnectAttempt = false;
this.onopen(event);
};
this.ws.onclose = (event:CloseEvent) => {
clearTimeout(timeout);
this.ws = null;
if (this.forcedClose) {
this.readyState = WebSocket.CLOSED;
this.onclose(event);
} else {
this.readyState = WebSocket.CONNECTING;
this.onconnecting();
if (!reconnectAttempt && !this.timedOut) {
this.log('ReconnectingWebSocket', 'onclose', this.url);
this.onclose(event);
}
setTimeout(() => {
this.connect(true);
}, this.reconnectInterval);
}
};
this.ws.onmessage = (event) => {
this.log('ReconnectingWebSocket', 'onmessage', this.url, event.data);
this.onmessage(event);
};
this.ws.onerror = (event) => {
this.log('ReconnectingWebSocket', 'onerror', this.url, event);
this.onerror(event);
};
}
public send(data:any) {
if (this.ws) {
this.log('ReconnectingWebSocket', 'send', this.url, data);
return this.ws.send(data);
} else {
throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';
}
}
/**
* Returns boolean, whether websocket was FORCEFULLY closed.
*/
public close():boolean {
if (this.ws) {
this.forcedClose = true;
this.ws.close();
return true;
}
return false;
}
/**
* Additional public API method to refresh the connection if still open (close, re-open).
* For example, if the app suspects bad data / missed heart beats, it can try to refresh.
*
* Returns boolean, whether websocket was closed.
*/
public refresh():boolean {
if (this.ws) {
this.ws.close();
return true;
}
return false;
}
private log(...args: any[]) {
if (this.debug || ReconnectingWebSocket.debugAll) {
console.debug.apply(console, args);
}
}
}
export = ReconnectingWebSocket;