Node.js
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.
Exercise 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.
Show example solution
const socketIo = require("socket.io");
const io = socketIo();
io.on("connection", (socket) => { console.log("Connected: " + socket.id); });
console.log("io.on ready");
Test yourself
-
Complete the io.on call
io.on("connection", (____) => { console.log("Connected"); });
Show answer
io.on("connection", (socket) => { console.log("Connected"); });
-
Match each piece to its role
- io.on("connection")
- Listens for new connections
- socket
- A single client
- socket.id
- Client identifier
- disconnect
- When the connection closes
-
When is io.on('connection') called?
io.on("connection", (socket) => {})
- When a new client connects
- When the server closes
- When a room is deleted
- When a message is sent
Show answer
When a new client connects — It is called when a new client connects.
Next lesson: emit and on