CodeBlanks Logo Icon CodeBlanks

Rooms

Learn room management with Socket.io rooms.

Rooms

A room is a channel that groups clients. With socket.join("roomName") you add a client to a room. Then io.to("roomName").emit(...) sends a message only to clients in that room.

Example: socket.join("room-42"); io.to("room-42").emit("message", "Hello room");. This sends Hello room to clients who joined room-42. Rooms are ideal for group chat, channel-based notifications and multiplayer games. With socket.leave("roomName") you remove a client from a room. Room names are strings; you can name them anything.

io.to('room').emit

To send a message to a room you use io.to("room").emit(event, data). This delivers the message only to clients in that room. io.emit goes to all clients; io.to goes to a single room.

Example: io.to("room-42").emit("message", { text: "Hello" });. All clients in room-42 receive the message event. To send to multiple rooms you write io.to("room-1").to("room-2").emit(...). Rooms are kept on the server side; they are invisible to the client. With socket.broadcast.to("room").emit(...) you send to other clients in the room (not yourself).

Practice Room join and broadcast

Use the io object below. Define io.on("connection", (socket) => { socket.join("room-42"); io.to("room-42").emit("message", "Hello"); }). Print "rooms ready" with console.log.

Starter code

index.js
const socketIo = require("socket.io");
const io = socketIo();

// Inside io.on, write socket.join and io.to calls
// write here

// Print "rooms ready"
// write here

Sample solution

index.js
const socketIo = require("socket.io");
const io = socketIo();
io.on("connection", (socket) => {
  socket.join("room-42");
  io.to("room-42").emit("message", "Hello");
});
console.log("rooms ready");

Expected output

rooms ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does socket.join('room-1') do?

index.js
socket.join("room-1")
  • Deletes the client
  • Adds the client to the room Correct answer
  • Sends a message to all clients
  • Closes the server

Explanation: socket.join adds the client to the room.

2 Complete the socket.join line

Question
socket.join("____");
Answer
socket.join("oda-42");

Explanation: socket.join('oda-42') adds the client to the room.

3 Match each piece to its role

Term Meaning
socket.join Adds client to room
socket.leave Removes client from room
io.to Sends to that room
room name Channel identifier

All lessons in Advanced