Room.ts
1.98 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
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
import { Connection } from "../connection/Connection";
import { v4 as uuidv4 } from "uuid";
import { RoomDescription, RoomInfo } from "./types";
import {
Message,
RoomChatMessage,
RoomUserUpdateMessage,
} from "../message/types";
import { UserData } from "../user/types";
import { User } from "../user/User";
export class Room {
public readonly uuid: string;
public name: string;
public readonly maxUsers: number;
private users: User[] = [];
private closed: boolean = false;
constructor(name: string, maxUsers: number = 8) {
this.uuid = uuidv4();
this.name = name;
this.maxUsers = maxUsers;
}
public connect(user: User): void {
if (this.users.includes(user) || this.users.length >= this.maxUsers) {
return;
}
this.broadcast(new RoomUserUpdateMessage("added", user.getData()));
this.users.push(user);
user.room = this; // TODO: 더 나은 관리
}
public disconnect(user: User): void {
const index = this.users.indexOf(user);
if (index > -1) {
this.users.splice(index, 1);
user.room = undefined;
this.broadcast(new RoomUserUpdateMessage("removed", user.getData()));
}
}
public sendChat(user: User, message: string): void {
this.broadcast(new RoomChatMessage(message, user.username), user);
}
public getDescription(): RoomDescription {
return {
uuid: this.uuid,
name: this.name,
currentUsers: this.users.length,
maxUsers: this.maxUsers,
};
}
public getInfo(): RoomInfo {
var users: UserData[] = this.users.map((u) => u.getData());
return {
uuid: this.uuid,
name: this.name,
maxUsers: this.maxUsers,
users: users,
};
}
public broadcast(message: Message, except?: User): void {
this.users.forEach((u) => {
if (u !== except) {
u.connection.send(message);
}
});
}
public close(): void {
if (!this.closed) {
this.users.forEach((u) => this.disconnect(u));
this.closed = true;
}
}
}