logo

Babylon.js Market

By Lawrence

5 minutes

Last lesson we built a room server. It hands out seats and creates one shared secret seed. The server works, but no one can reach it yet. There is no way in. You can't type a code, send a link to a friend, or turn "a server is running" into "I'm in seat 2." That missing piece is client code. It runs before the scene loads. You can't open a peer mesh until you know your own seat at the table.

All of that pre-scene work lives in one module, roomClient.ts. It is just plain functions. There is no System and no EventBus yet. The functions do one job. They figure out which seat a browser gets. Then they split that answer into the two inputs the networked scene needs.

Generate a room code

A room needs a short name. It should be easy to read aloud over the phone. generateRoomCode makes one. It is six letters, nothing more.

From the room client:

src/components/P2PNetwork/roomClient.ts
const ROOM_CODE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const ROOM_CODE_LENGTH = 6;

/**
 * A shareable room code: `ROOM_CODE_LENGTH` random letters. The randomness is
 * injectable (defaulting to `Math.random`) so a test gets a deterministic code.
 */
export function generateRoomCode(rand: () => number = Math.random): string {
  let code = '';
  for (let i = 0; i < ROOM_CODE_LENGTH; i++) {
    code += ROOM_CODE_ALPHABET[Math.floor(rand() * ROOM_CODE_ALPHABET.length)];
  }
  return code;
}

The randomness is an argument. It defaults to Math.random. A test can pass in its own value to get the same code every time. Call the function with no arguments and you get a string. Drop that string straight into the address bar:

const code = generateRoomCode();
// → 'ABCDEF'
history.replaceState(null, '', `?room=${code}`);
// the URL is now the invite — copy it, send it

The host makes the code once. Everyone else opens the link and reads ?room= back out of the URL. The code is the meeting point. It is the public handle that every browser POSTs to.

Continue reading

Unlock the Full Course

Every lesson, the runnable examples, and the finished build — yours to keep.

$9one-time

Was this page helpful?

We read every note — tell us what's working and what isn't.

↑↓ NavigateEnter SelectEsc CloseCtrl+K Open Search