📡 Step-by-Step Guide to Using Socket.IO for Real-Time Apps
Learn how to use Socket.IO to make your web apps communicate in real-time. This guide explains every step with code examples for chat apps, live notifications, and collaborative tools.
1️⃣ Install Socket.IO
First, you need to install Socket.IO on your server and client.
// Server
npm install socket.io
// Client (browser)
npm install socket.io-client
2️⃣ Create the Server
Import Socket.IO and attach it to your server.
import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: { origin: "*" } // allow all clients for testing
});
io.on("connection", (socket) => {
console.log("User connected:", socket.id);
// Example: Receive message from client
socket.on("sendMessage", (msg) => {
console.log("Message received:", msg);
socket.broadcast.emit("receiveMessage", msg);
});
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id);
});
});
httpServer.listen(3000, () => console.log("Server running on port 3000"));
3️⃣ Create the Client
Connect to the server and send/receive messages.
import { io } from "socket.io-client";
const socket = io("http://localhost:3000");
// Send a message
socket.emit("sendMessage", "Hello World!");
// Listen for messages
socket.on("receiveMessage", (msg) => {
console.log("New message:", msg);
});
4️⃣ Real-Time Notifications
You can also use Socket.IO to notify users immediately when something happens.
// Server triggers notification
function notifyUser(userId, message) {
const userSockets = connectedUsers[userId] || [];
userSockets.forEach(socketId => io.to(socketId).emit("newNotification", message));
}
// Client receives notification
socket.on("newNotification", (msg) => {
alert("🔔 " + msg);
});
5️⃣ Collaborative Apps
Multiple users can interact in real-time, like editing a document or drawing together.
// Example: Drawing app
socket.emit("draw", { x: 100, y: 200 });
socket.on("draw", (data) => {
drawOnCanvas(data.x, data.y);
});
🧸 How Socket.IO Works Step by Step
1️⃣ Browser connects to the server.
2️⃣ Browser sends a message using emit.
3️⃣ Server receives it and sends it to other users.
4️⃣ Browser listens using on.
5️⃣ When users disconnect, the server updates online status automatically.
Made with ❤️ by Jhalak | Step-by-Step Socket.IO Guide
Comments
Post a Comment