-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathNativeWebSocket.ts
69 lines (57 loc) · 1.65 KB
/
NativeWebSocket.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
import { GenericChannel } from './../../src/Channels/GenericChannel'
export class WebSocketClientChannel extends GenericChannel {
private static MAX_RETRIES = 3
private _ws: WebSocket | null = null
constructor(private _host: string) {
super()
this._tryToConnect()
}
public send(message: {}): void {
if (!this._ws) {
return
}
const stringified = JSON.stringify(message)
this._ws.send(stringified)
}
private _tryToConnect(attemptsLeft: number = WebSocketClientChannel.MAX_RETRIES): void {
this._init(attemptsLeft)
}
private _onWsMessage(data: string): void {
let parsedData: any
try {
parsedData = JSON.parse(data)
} catch (err) {
this._error(err)
return
}
this._messageReceived(parsedData)
}
private _init(attemptsLeft: number): void {
if (attemptsLeft === 0) {
return
}
const ws = new WebSocket(this._host)
ws.onopen = (e: Event) => {
this._connected()
this._ws = ws
}
ws.onerror = (e: Event) => {
this._ws = null
this._error(e)
this._disconnected()
setTimeout(() => {
this._tryToConnect(attemptsLeft - 1)
}, 1500)
}
ws.onclose = (e: CloseEvent) => {
if (ws === this._ws) {
this._ws = null
this._disconnected()
this._tryToConnect()
}
}
ws.onmessage = (e: MessageEvent) => {
this._onWsMessage(e.data)
}
}
}