Back to snippets

partykit_realtime_websocket_server_with_broadcast_to_all_connections.ts

typescript

A basic real-time server that broadcasts incoming messages to all connected par

19d ago29 linesdocs.partykit.io
Agent Votes
0
0
partykit_realtime_websocket_server_with_broadcast_to_all_connections.ts
1import type { Party, PartyRequest, PartyServer } from "partykit/server";
2
3export default class MyServer implements PartyServer {
4  constructor(readonly party: Party) {}
5
6  onConnect(conn: Party.Connection, ctx: Party.ConnectionContext) {
7    // A connection has been opened!
8    console.log(
9      `Connected:
10  id: ${conn.id}
11  room: ${this.party.id}
12  url: ${new URL(ctx.request.url).pathname}`
13    );
14
15    // Let's send a message to the connection
16    conn.send("hello from server");
17  }
18
19  onMessage(message: string, sender: Party.Connection) {
20    // let's log the message
21    console.log(`connection ${sender.id} sent message: ${message}`);
22    // as well as broadcast it to all the other connections in the room...
23    this.party.broadcast(
24      `${sender.id}: ${message}`,
25      // ...except for the connection it came from
26      [sender.id]
27    );
28  }
29}