-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
73 lines (58 loc) · 1.72 KB
/
server.ts
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
import type * as Party from "partykit/server";
interface Design {
shapes: Array<any>;
filters: Array<any>;
}
export default class Server implements Party.Server {
constructor(readonly room: Party.Room) {}
// Store connected clients and their data
connections = new Map<string, WebSocket>();
designs: Record<string, Design> = {};
async onConnect(conn: Party.Connection) {
// Store new connection
this.connections.set(conn.id, conn);
// Send current state to new connection
conn.send(JSON.stringify({
type: 'init',
designs: this.designs,
users: Array.from(this.connections.keys())
}));
// Broadcast updated users list to all clients
this.broadcastConnections();
}
async onClose(conn: Party.Connection) {
// Remove disconnected user
this.connections.delete(conn.id);
// Broadcast updated users list to all clients
this.broadcastConnections();
}
async onMessage(message: string, sender: Party.Connection) {
try {
const data = JSON.parse(message);
switch (data.type) {
case 'update_design':
this.designs[sender.id] = data.design;
this.broadcastDesigns();
break;
// Add other message type handlers as needed
}
} catch (e) {
console.error('Error processing message:', e);
}
}
private broadcastConnections() {
const message = JSON.stringify({
type: 'users',
users: Array.from(this.connections.keys())
});
this.room.broadcast(message);
}
private broadcastDesigns() {
const message = JSON.stringify({
type: 'designs',
designs: this.designs
});
this.room.broadcast(message);
}
}
Server satisfies Party.Worker;