Handling connection events lets your app know when users connect or disconnect. This helps you manage real-time interactions smoothly.
You want to greet users when they join a chat room.
You need to track how many users are online.
You want to clean up resources when a user leaves.
You want to log connection times for analytics.
Syntax
Express
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
io.on('connection', (socket) => {
// code to run when a user connects
socket.on('disconnect', () => {
// code to run when a user disconnects
});
});
server.listen(3000);
The connection event runs when a user connects.
The disconnect event runs when a user leaves.
Examples
This logs a message every time a user connects.
Express
io.on('connection', (socket) => {
console.log('A user connected');
});
This program starts a server that listens for users connecting and disconnecting. It logs their connection status and sends a welcome message when they join.
Express
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.emit('welcome', 'Welcome to the server!');
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
OutputSuccess
Important Notes
Each user connection has a unique socket.id to identify them.
Use connection events to manage real-time features like chat or notifications.
Summary
Connection events let you detect when users join or leave.
Use io.on('connection') to run code on user connect.
Use socket.on('disconnect') to run code on user disconnect.
Practice
(1/5)
1. What does io.on('connection', callback) do in an Express app using Socket.IO?
easy
A. Runs the callback when a user disconnects
B. Runs the callback when the server starts
C. Runs the callback when a new user connects to the server
D. Runs the callback when the server shuts down
Solution
Step 1: Understand the event name 'connection'
The 'connection' event triggers when a new client connects to the server.
Step 2: Understand the role of the callback
The callback runs code to handle the new connection, such as setting up listeners.
Final Answer:
Runs the callback when a new user connects to the server -> Option C
Quick Check:
io.on('connection') = new user connected [OK]
Hint: Remember 'connection' means user joined [OK]
Common Mistakes:
Confusing 'connection' with 'disconnect'
Thinking it runs on server start
Assuming it runs on server shutdown
2. Which of the following is the correct syntax to listen for a user disconnect event on a socket?
easy
A. io.on('disconnect', () => { /* code */ })
B. socket.on('disconnect', () => { /* code */ })
C. socket.emit('disconnect', () => { /* code */ })
D. io.emit('disconnect', () => { /* code */ })
Solution
Step 1: Identify the object to listen on
The disconnect event is listened on the individual socket, not the io server object.
Step 2: Use the correct method and event name
Use socket.on('disconnect', callback) to run code when that socket disconnects.
Hint: Use socket only inside connection callback [OK]
Common Mistakes:
Trying to use socket outside connection event
Confusing event names 'disconnect' vs 'disconnected'
Ignoring scope errors
5. You want to broadcast a message to all connected users except the one who just connected. Which code inside io.on('connection', (socket) => { ... }) correctly does this when a user connects?
hard
A. socket.on('message', 'A new user joined')
B. io.emit('message', 'A new user joined')
C. socket.emit('message', 'A new user joined')
D. socket.broadcast.emit('message', 'A new user joined')
Solution
Step 1: Understand broadcast
socket.broadcast.emit sends to all except the current socket.
Step 2: Compare options
io.emit sends to all including current socket; socket.emit sends only to current socket; socket.on listens, not sends.
Final Answer:
socket.broadcast.emit('message', 'A new user joined') -> Option D
Quick Check:
Broadcast excludes sender, perfect for this case [OK]
Hint: Use socket.broadcast.emit to exclude sender [OK]
Common Mistakes:
Using io.emit which sends to sender too
Using socket.emit which sends only to sender
Confusing emit with on
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.