-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectionProvider.tsx
80 lines (64 loc) · 2.34 KB
/
ConnectionProvider.tsx
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
// TODO this module should provide automatic reconnection in the future
// see https://github.com/cueglow/glowdtf/issues/52
import { ClientMessage } from "./ClientMessage";
import { MessageHandler } from "./MessageHandler";
import { SubscriptionProvider } from "./SubscriptionProvider";
export enum ConnectionState {
Connecting,
Open,
Closed,
}
const webSocketPath = "ws://" + window.location.host + "/webSocket";
const pingDelay = 1*60*1000; // 1 minute in ms
const pingMessage = JSON.stringify({event: "ping"})
class Connection {
readonly webSocket;
readonly subscriptions;
readonly messageHandler;
constructor() {
this.webSocket = new WebSocket(webSocketPath);
// regularly send ping messages to prevent WebSocket timeout
this.webSocket.addEventListener(
"open", () => setInterval(() => {
this.webSocket.send(pingMessage)
}, pingDelay)
)
this.subscriptions = new SubscriptionProvider(this.webSocket);
this.messageHandler = new MessageHandler(this.webSocket);
}
}
export const connectionProvider = new class {
readonly connection = new Connection();
send(message: ClientMessage) {
const str = JSON.stringify(message)
this.connection.webSocket.send(str)
}
private _connectionState = mapReadyStateToConnectionState(
this.connection.webSocket.readyState
)
get connectionState() { return this._connectionState; }
onConnectionChange = (newConnectionState: ConnectionState) => { };
constructor() {
// add webSocket event listeners
this.connection.webSocket.addEventListener(
"open", () => {
this._connectionState = ConnectionState.Open;
this.onConnectionChange(ConnectionState.Open);
}
);
this.connection.webSocket.addEventListener(
"close", () => {
this._connectionState = ConnectionState.Closed;
this.onConnectionChange(ConnectionState.Closed);
}
);
}
}()
function mapReadyStateToConnectionState(readyState: Number) {
switch (readyState) {
case 0: return ConnectionState.Connecting;
case 1: return ConnectionState.Open;
case 2: return ConnectionState.Closed;
case 3: return ConnectionState.Closed;
}
}