io.on
- Node.js course
- Advanced
- Lesson 44/83
- 5 min
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
const socketIo = require("socket.io");
// Create io and define a connection handler
// write here
// Print "io.on ready"
// write hereSample solution
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
io.on("connection", (____) => { console.log("Connected"); });
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?
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.