Room.ts
1.31 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
56
import { Connection } from "../connection/Connection";
import { v4 as uuidv4 } from "uuid";
import { RoomData } from "./types";
export class Room {
public readonly uuid: string;
public name: string;
public readonly maxConnections: number;
private connections: Connection[] = [];
private closed: boolean = false;
constructor(name: string, maxConnections: number = 8) {
this.uuid = uuidv4();
this.name = name;
this.maxConnections = maxConnections;
}
public connect(connection: Connection): void {
if (
this.connections.includes(connection) ||
this.connections.length >= this.maxConnections
) {
return;
}
this.connections.push(connection);
connection.room = this; // TODO: 더 나은 관리
}
public disconnect(connection: Connection): void {
const index = this.connections.indexOf(connection);
if (index > -1) {
this.connections.splice(index, 1);
connection.room = undefined;
}
}
public getData(): RoomData {
return {
uuid: this.uuid,
name: this.name,
currentConnections: this.connections.length,
maxConnections: this.maxConnections,
};
}
public close(): void {
if (!this.closed) {
this.connections.forEach((connection) => this.disconnect(connection));
this.closed = true;
}
}
}