Socket.io is a powerful JavaScript library that enables real-time, bidirectional, and event-based communication between web clients and servers. It is widely used in modern web applications such as chat apps, live notifications, gaming platforms, and collaborative tools.
Unlike traditional HTTP-based communication, Socket.io uses WebSockets (and fallbacks like long polling) to maintain a persistent connection between the client and server. This makes it highly efficient for real-time data transfer.
Socket.io simplifies real-time communication by abstracting complex WebSocket handling and providing a robust API. It ensures compatibility across browsers and networks, making it a preferred choice for developers.
Before setting up Socket.io, ensure you have the following:
node -v
npm -v
To start using Socket.io, you need to install it in your Node.js project.
mkdir socketio-app
cd socketio-app
npm init -y
npm install express socket.io
Here, Express is used to create the server, while Socket.io enables real-time communication.
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);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
<!DOCTYPE html>
<html>
<head>
<title>Socket.io Example</title>
</head>
<body>
<h1>Socket.io Real-Time App</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
socket.on('connect', () => {
console.log('Connected to server');
});
</script>
</body>
</html>
Socket.io uses custom events for communication between client and server.
io.on('connection', (socket) => {
socket.emit('welcome', 'Welcome to Socket.io server!');
});
socket.on('welcome', (message) => {
console.log(message);
});
socket.emit('message', 'Hello Server');
socket.on('message', (data) => {
console.log(data);
});
io.emit('broadcast', 'Message to all users');
socket.broadcast.emit('broadcast', 'Message to others');
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
<input id="msg" />
<button onclick="sendMessage()">Send</button>
<script>
function sendMessage() {
const msg = document.getElementById('msg').value;
socket.emit('chat message', msg);
}
socket.on('chat message', (msg) => {
console.log(msg);
});
</script>
socket.join('room1');
io.to('room1').emit('message', 'Hello Room 1');
const nsp = io.of('/chat');
nsp.on('connection', (socket) => {
console.log('User connected to chat namespace');
});
io.on('connection', (socket) => {
socket.on('error', (err) => {
console.error('Error:', err);
});
});
npm install @socket.io/redis-adapter redis
const { createAdapter } = require('@socket.io/redis-adapter');
const { createClient } = require('redis');
const pubClient = createClient();
const subClient = pubClient.duplicate();
io.adapter(createAdapter(pubClient, subClient));const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
io.use((socket, next) => {
if (socket.handshake.auth.token) {
next();
} else {
next(new Error("Authentication error"));
}
});
socket.on('disconnect', () => {
console.log('Disconnected');
});
socket.on('reconnect', () => {
console.log('Reconnected');
});
Setting up Socket.io is a fundamental step toward building real-time web applications. From installation to advanced features like rooms, namespaces, and scaling, Socket.io provides a complete ecosystem for seamless communication between client and server.
By mastering Socket.io setup, developers can build scalable, high-performance applications that deliver instant updates and enhanced user experiences.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved