Tutorial
A real-time multiplayer game
A drawing and guessing game, for several players, live in the browser. WebSockets go through the app's address with no setup.
One player draws a word, the others guess in the chat, the fastest scores. Every stroke has to appear for everyone the moment it's drawn: that takes a connection that stays open between each browser and the server, a WebSocket. On Kazibo, it goes through the app's address like everything else.
What you say
Make a drawing and guessing game to play with several people in the browser: one player draws a word, the others guess in the chat, points for the fastest. Real time with WebSockets. Use kazibo to put it online, with a readable address.
What happens
- The agent writes a Node server that serves the page and the WebSockets on the same port: an app has one address and one port.
- The app's address lets WebSockets through as they are, without cutting a connection that stays open a long time.
- Every deploy restarts the server and closes the connections: the page reconnects by itself, a little later on each try. The agent writes this from the start.
- You asked for a readable address: a game is meant to be shared.
Playing
Send the link to your friends: each opens it on their phone or computer, and the game starts. If the address is already taken, the agent suggests another one.
Going further
- "Keep the leaderboard from one game to the next": the scores go on the app's data disk, which survives deploys.
- "Show the players' real names": with Kazibo sign-in in
optionalmode. - "Keep the game online for good", then "show it in the community": it appears on the Community page, where others can find it.
For the curious: the server and reconnecting
The server shares the app's port between the page and the WebSockets, with the ws library:
const http = require("node:http");
const { WebSocketServer } = require("ws");
const port = Number(process.env.PORT || 80);
const server = http.createServer(servePage);
const wss = new WebSocketServer({ server, path: "/ws" });
wss.on("connection", (socket) => {
socket.on("error", console.error);
socket.on("message", (data) => {
for (const client of wss.clients) client.send(data.toString());
});
});
// A deploy restarts the service: close every connection, then exit.
process.on("SIGTERM", () => {
for (const client of wss.clients) client.close(1012, "restarting");
server.close(() => process.exit(0));
});
server.listen(port, "0.0.0.0");In the page, the browser comes back after every cut:
let delay = 500;
function connect() {
const socket = new WebSocket(location.origin.replace(/^http/, "ws") + "/ws");
socket.onopen = () => (delay = 500);
socket.onmessage = (event) => draw(JSON.parse(event.data));
socket.onclose = () => {
setTimeout(connect, delay);
delay = Math.min(delay * 2, 10000);
};
}
connect();