-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.ts
More file actions
36 lines (29 loc) · 1019 Bytes
/
chat.ts
File metadata and controls
36 lines (29 loc) · 1019 Bytes
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
import {
WebSocket,
isWebSocketCloseEvent,
} from "https://deno.land/std/ws/mod.ts";
import { v4 } from "https://deno.land/std/uuid/mod.ts";
const users = new Map<string,WebSocket>();
function broadcast(message: string, senderID?: string): void {
if(!message) return
for (const user of users.values()) {
user.send(senderID ? `[${senderID}]: ${message}` : message);
}
}
export async function chat(ws: WebSocket): Promise<void> {
const userID = v4.generate();
// Register user connection
users.set(userID, ws);
broadcast(`> User with the id ${userID} is connected`);
// Wait for new messages
for await (const event of ws) {
const message = typeof event === 'string' ? event : ''
broadcast(message, userID);
// Unregister user connection
if (!message && isWebSocketCloseEvent(event)) {
users.delete(userID);
broadcast(`> User with the id ${userID} is disconnected`);
break;
}
}
}