-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathhub.ts
More file actions
49 lines (41 loc) · 1.27 KB
/
hub.ts
File metadata and controls
49 lines (41 loc) · 1.27 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
import http from 'node:http';
type Client = {
id: string;
roomId: string;
res: http.ServerResponse;
};
// class Hub maintains the client connections in memory
// In practice, you could use something like Redis PubSub to work out the pub/sub part
export class Hub {
constructor(private readonly clients: Map<string, Client> = new Map()) {}
addClient(client: Client) {
console.log('adding client', client.id);
this.clients.set(client.id, client);
}
removeClient(id: string) {
console.log('removing client', id);
this.clients.delete(id);
}
broadcast(roomId: string, data: unknown) {
console.log(`broadcasting to ${this.clients.size}...`);
for (const client of this.clients.values()) {
if (client.roomId === roomId) {
this.writeToClient(client.id, data);
}
}
}
send(id: string, data: unknown) {
console.log(`sending to a single client: ${id}`);
const successful = this.writeToClient(id, data);
if (!successful) {
console.warn(`no client with id ${id} found`);
}
}
private writeToClient(id: string, data: unknown) {
if (!this.clients.has(id)) {
return false;
}
this.clients.get(id)?.res.write(`data: ${JSON.stringify(data)}\n\n`);
}
}
export const hubInstance = new Hub(new Map());