CodeBlanks Logo Icon CodeBlanks

io.on

Learn to accept connections with io.on('connection').

io.on('connection', ...)

io.on("connection", callback) is called when a new client connects. The callback receives a socket parameter that represents the connecting client. This is the heart of a Socket.io server.

Example: io.on("connection", (socket) => { console.log("Client connected"); });. When a client connects, "Client connected" is printed. Through the socket object you listen to that client's events and send messages. The connection event name is fixed; Socket.io triggers it automatically. io.on can listen to other events but connection is the most common.

The socket parameter

The callback's socket parameter represents the connecting client. Through this object you send messages to the client and listen to its events. Each connection creates a new socket.

Example: io.on("connection", (socket) => { console.log(socket.id); });. socket.id is a unique identifier for each client. With socket.emit you send messages to the client; with socket.on you listen to events from the client. When a client disconnects, socket.on("disconnect", ...) fires. Without socket you cannot work with a single client; io addresses all clients, socket addresses one.

Practice Define a connection handler

Use the socketIo module below. Create io with const io = socketIo(). Define io.on("connection", (socket) => { console.log("Connected: " + socket.id); }). Print "io.on ready" with console.log.

Starter code

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

// Create io and define a connection handler
// write here

// Print "io.on ready"
// write here

Sample solution

index.js
const socketIo = require("socket.io");
const io = socketIo();
io.on("connection", (socket) => { console.log("Connected: " + socket.id); });
console.log("io.on ready");

Expected output

io.on ready

Questions and answers

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

1 Complete the io.on call

Question
io.on("connection", (____) => { console.log("Connected"); });
Answer
io.on("connection", (socket) => { console.log("Connected"); });

Explanation: The callback takes the socket parameter.

2 Match each piece to its role

Term Meaning
io.on("connection") Listens for new connections
socket A single client
socket.id Client identifier
disconnect When the connection closes

3 When is io.on('connection') called?

index.js
io.on("connection", (socket) => {})
  • When a new client connects Correct answer
  • When the server closes
  • When a room is deleted
  • When a message is sent

Explanation: It is called when a new client connects.

All lessons in Advanced