Building a WebSocket server
Every PartyKit server accepts WebSocket connections by default:
You can connect to it using the PartySocket
client library.
This will automatically open a WebSocket connection to the PartyKit server at ws://localhost:1999/party/my-room
, and send a greeting message.
The room
id, in this case "my-room"
, uniquely identifies the room that youâre connecting to. Each time you use a new room id, a new PartyServer instance is created.
This means that two clients connecting with the same room
id will always be connected to the same server and can communicate to each other. In other words, creating new server instances is as easy as using a new id.
Handling incoming messages
However, the server doesnât do anything yet! Letâs fix that by adding an onMessage
handler that receives all incoming messages, and sends them along to all other connected clients:
Now, every connected client will instantly see the same message in their browser console:
07f60783-d421-4ce4-a408-5e1c0588c2d2 says: Hey everyone!
This works, because the Room
maintains references to all connected clients. You can access them using the Room.getConnections()
method.
This pattern is called âbroadcastingâ â a message from one client is received and sent to everyone. In fact, this use case is so common that PartyKit includes a broadcast
utility method that does the same thing as the for...of
loop through connections.
The above can be simplified to:
Thatâs it! Weâve implemented a simple WebSocket broadcast server in just 5 lines of code.
Handling connection events
Letâs make our server a little friendlier and notify other members when new users connect and disconnect:
Now, when you connect to the server, youâll see the following message:
Welcome, 07f60783-d421-4ce4-a408-5e1c0588c2d2
And every other connected client will see the following:
Heads up! 07f60783-d421-4ce4-a408-5e1c0588c2d2 joined the party!
Putting into action
Thatâs all it takes to create a real-time WebSocket server with PartyKit. To learn more about common patterns and uses cases, head over to the Examples section.