How to Use Socket.io in Node.js for Real-Time Communication
To use
socket.io in Node.js, first install it with npm install socket.io. Then, create a server using http or express, attach socket.io to it, and listen for client connections and events to enable real-time communication.Syntax
Here is the basic syntax to set up socket.io with a Node.js server:
- Import modules: Load
httpandsocket.io. - Create server: Use
http.createServer()or an Express app. - Attach socket.io: Pass the server to
socket.io(). - Listen for connections: Use
io.on('connection', callback)to handle clients. - Handle events: Use
socket.on(event, callback)andsocket.emit(event, data)to communicate.
javascript
const http = require('http'); const { Server } = require('socket.io'); const server = http.createServer(); const io = new Server(server); io.on('connection', (socket) => { console.log('A user connected'); socket.on('message', (msg) => { console.log('Message received:', msg); socket.emit('reply', 'Message received loud and clear'); }); }); server.listen(3000, () => { console.log('Server listening on port 3000'); });
Output
Server listening on port 3000
A user connected
Message received: Hello server
Example
This example shows a simple Node.js server using socket.io that listens for a chat message from a client and broadcasts it back to all connected clients.
javascript
const http = require('http'); const { Server } = require('socket.io'); const server = http.createServer(); const io = new Server(server); io.on('connection', (socket) => { console.log('User connected'); socket.on('chat message', (msg) => { console.log('Message:', msg); io.emit('chat message', msg); // broadcast to all clients }); socket.on('disconnect', () => { console.log('User disconnected'); }); }); server.listen(3000, () => { console.log('Listening on *:3000'); });
Output
Listening on *:3000
User connected
Message: Hello everyone
User disconnected
Common Pitfalls
Some common mistakes when using socket.io in Node.js include:
- Not attaching
socket.ioto the same server instance that listens for HTTP requests. - Forgetting to handle the
connectionevent before listening for custom events. - Using
socket.emitinstead ofio.emitwhen you want to broadcast to all clients. - Not handling client disconnections properly.
javascript
/* Wrong: Creating separate servers for HTTP and socket.io */ const http = require('http'); const { Server } = require('socket.io'); const httpServer = http.createServer(); const io = new Server(); // Not attached to httpServer io.on('connection', (socket) => { console.log('User connected'); }); httpServer.listen(3000); /* Right: Attach socket.io to the HTTP server */ const http2 = require('http'); const { Server: Server2 } = require('socket.io'); const server = http2.createServer(); const io2 = new Server2(server); io2.on('connection', (socket) => { console.log('User connected'); }); server.listen(3000);
Quick Reference
Remember these key points when using socket.io in Node.js:
- Install with
npm install socket.io. - Attach
socket.ioto your HTTP server. - Use
io.on('connection')to detect clients. - Use
socket.onandsocket.emitfor client-specific events. - Use
io.emitto broadcast to all clients.
Key Takeaways
Install socket.io and attach it to your Node.js HTTP server to enable real-time communication.
Use io.on('connection') to handle new client connections and socket.on to listen for events from clients.
Use socket.emit to send messages to a single client and io.emit to broadcast to all connected clients.
Always handle client disconnections to keep your server state clean.
Avoid creating separate servers for HTTP and socket.io; attach socket.io to the existing HTTP server.