-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathWebSocket.ts
108 lines (99 loc) · 2.83 KB
/
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
import * as WebSocket from 'ws'
import { Server as WebSocketServer } from 'ws'
import { GenericChannel } from './../../src/Channels/GenericChannel'
export class WebSocketClientChannel extends GenericChannel {
private static _MAX_RETRIES = 3
private _tries = 0
private _ws: WebSocket | null
constructor(private _host: string) {
super()
this._init()
}
private _init(): void {
if (++this._tries === WebSocketClientChannel._MAX_RETRIES) {
return
}
const reinit = () => {
this._disconnected()
this._ws = null
this._init()
}
let ws: WebSocket | null = null
try {
ws = new WebSocket(this._host)
} catch (err) {
setTimeout(() => this._init, 500)
}
(ws as WebSocket).on('open', () => {
this._ws = ws as WebSocket
this._ws.on('close', reinit)
this._ws.on('error', e => {
this._error(e)
reinit()
})
this._ws.on('message', (message: string) => {
let parsedData
try {
parsedData = JSON.parse(message)
} catch (err) {
return
}
this._messageReceived(parsedData)
})
this._connected()
})
}
send(message: {}) {
if (!this._ws) {
return
}
this._ws.send(JSON.stringify(message))
}
}
export class WebSocketServerChannel extends GenericChannel {
private static _MAX_RETRIES = 3
private _tries = 0
private _ws: WebSocket | null
constructor(private _port: number) {
super()
this._init()
}
private _init(): void {
if (++this._tries === WebSocketServerChannel._MAX_RETRIES) {
return
}
const server = new WebSocketServer({ port: this._port })
const reinit = () => {
this._disconnected()
this._ws = null
server.close(() => {
this._init()
})
}
server.on('connection', ws => {
this._ws = ws
this._ws.on('close', reinit)
this._ws.on('error', e => {
this._error(e)
reinit()
})
this._ws.on('message', (message: string) => {
let parsedData
try {
parsedData = JSON.parse(message)
} catch (err) {
this._error(err)
return
}
this._messageReceived(parsedData)
})
this._connected()
})
}
send(message: {}) {
if (!this._ws) {
return
}
this._ws.send(JSON.stringify(message))
}
}