-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.ts
More file actions
55 lines (50 loc) · 1.89 KB
/
Copy pathsocket.ts
File metadata and controls
55 lines (50 loc) · 1.89 KB
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
import type { WebSocket } from "ws";
import { v4 } from "uuid";
/** An extendable base class for creating players. */
export abstract class Socket {
/** The `WebSocket` instance to be associated with the socket. */
protected readonly socket: WebSocket;
/** The socket's socket. */
public readonly id: string = v4();
/** The time between pings in seconds. */
protected readonly HEARTBEAT_INTERVAL_SECONDS: number;
/** Whether the client has responded with a `pong` since the last `ping`. */
private connectionAlive: boolean = true;
/** The timer responsible for the websocket heartbeat. */
private heartbeatInterval?: NodeJS.Timer;
/**
* Creates a new socket.
* @param socket The `WebSocket` instance to be associated with this socket.
* @param heartbeatIntervalSeconds The time between pings in seconds.
*/
public constructor(socket: WebSocket, heartbeatIntervalSeconds: number) {
this.socket = socket;
this.HEARTBEAT_INTERVAL_SECONDS = heartbeatIntervalSeconds;
this.startHeartbeat();
}
/**
* Pings the Client every `HEARTBEAT_INTERVAL` seconds and terminates
* the websocket connection if the client does not respond.
*/
private startHeartbeat() {
this.socket.on('pong', () => this.connectionAlive = true);
this.socket.on('close', () => {
this.onDisconnect();
if (this.heartbeatInterval) clearInterval(this.heartbeatInterval);
});
this.heartbeatInterval = setInterval(() => {
if (this.connectionAlive === false) {
this.socket.terminate();
this.onDisconnect();
}
this.connectionAlive = false;
this.socket.ping();
}, this.HEARTBEAT_INTERVAL_SECONDS * 1000);
}
/** Simply terminates the websocket encapsuled in the socket. */
public terminate() {
this.socket.terminate();
}
/** A function that is called when the websocket disconnects. */
protected abstract onDisconnect(): void;
}