CodeBlanks Logo Icon CodeBlanks

Summary - Realtime

Combine Socket.io, emit/on and rooms to write a room system.

Summary - Real-time

In this group you learned the core tools of Socket.io: creating an io with socketIo(server), listening to connections with io.on("connection"), exchanging messages with socket.emit and socket.on, grouping clients into rooms with socket.join, and creating namespaces with io.of.

Now you will combine these into a small chat server skeleton. The skeleton will greet new connections, listen for chat messages, and broadcast them to all clients. This mini task shows how real-time tools combine in a real server.

Chat server design

The skeleton of a chat server is this: io.on("connection") greets a new client, socket.on("chat") receives a message from the client, io.emit("chat") broadcasts it to all clients.

Flow: io.on("connection", (socket) => { socket.on("chat", (message) => { io.emit("chat", message); }); });. The client sends the chat event; the server listens and broadcasts to all. The event name must be the same on both sides. On top of this skeleton you can add authentication, room support and message persistence. Socket.io makes this flow possible with very little code.

Practice Build the chat skeleton

Use the io object below. Define the chat skeleton with io.on("connection", (socket) => { socket.on("chat", (mesaj) => { io.emit("chat", mesaj); }); }). Print "Chat ready" with console.log.

Starter code

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

// Combine connection + chat listener + io.emit broadcast
// write here

// Print "Chat ready"
// write here

Sample solution

index.js
const socketIo = require("socket.io");
const io = socketIo();
io.on("connection", (socket) => {
  socket.on("chat", (mesaj) => { io.emit("chat", mesaj); });
});
console.log("Chat ready");

Expected output

Chat ready

Questions and answers

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

1 What pieces does the chat skeleton combine?

index.js
io.on("connection", (socket) => socket.on("chat", ...))
  • Only require
  • Only console.log
  • Only socket.join
  • io.on, socket.on and io.emit Correct answer

Explanation: io.on + socket.on + io.emit combine.

2 Match each tool to its role

Term Meaning
io.on("connection") Listens for new clients
socket.on("chat") Receives a message
io.emit Broadcasts to all
socket.join Adds to a room

All lessons in Advanced