WebSockets and Socket.IO

Build a two-way event channel between a Node.js server and browser clients.

Lesson content

🎯 Goal By the end of this lesson, you'll understand: What is WebSocket? Why do we need WebSockets? What is Socket.IO? Difference between WebSocket and Socket.IO How WebSockets work Socket.IO examples Real-world examples Interview questions What is WebSocket? WebSocket is a communication protocol that provides a persistent, full-duplex connection between the client and the server. Once connected, both the client and the server can send messages at any time. Simple Definition: WebSocket creates a permanent two-way communication channel between the client and the server. Why Do We Need WebSockets? Normal HTTP: Client sends request Server sends response Connection closes For live applications, this is inefficient. WebSocket keeps the connection open. Real-Life Example 📞 Imagine a phone call. HTTP You Call │ Talk │ Call Ends WebSocket You Call │ Conversation Continues │ Both Can Speak Anytime HTTP vs WebSocket HTTP Client │ Request ▼ Server │ Response ▼ Connection Closed WebSocket Client ▲ │ Persistent Connection │ ▼ Server The connection stays open until either side closes it. Features of WebSocket Persistent Connection Full Duplex Communication Low Latency Efficient Real-Time Communication What is Socket.IO? Socket.IO is a JavaScript library that makes real-time communication easier by providing an event-based API. It commonly uses WebSocket when available and can fall back to other transports if necessary. Simple Definition: Socket.IO is a library built for real-time communication that provides additional features beyond the WebSocket protocol. Why Use Socket.IO? Socket.IO provides: Automatic Reconnection Event-Based Communication Rooms Namespaces Broadcasting Acknowledgements Install Socket.IO npm install socket.io Client Library npm install socket.io-client Express + Socket.IO Setup 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 ); server . listen( 3000 ); Detect Connection io . on( "connection" , ( socket ) => { console . log( "User Connected" ); }); Output User Connected Send Message socket . emit( "welcome" , "Welcome to Chat" ); Receive Message socket . on( "chat" , ( message ) => { console . log( message ); }); Output Hello Server Broadcast Message socket . broadcast . emit( "message" , "A New User Joined" ); All connected clients except the sender receive the message. Send to Everyone io . emit( "notification" , "Server Maintenance Tonight" ); Every connected client receives the notification. Join a Room socket . join( "room1" ); Send to a Room io . to( "room1" ) . emit( "message" , "Hello Room" ); Namespace Example const admin = io . of( "/admin" ); admin . on( "connection" , ( socket ) => { console . log( "Admin Connected" ); }); Disconnect Event socket . on( "disconnect" , () => { console . log( "User Left" ); }); WebSocket Handshake Before the persistent connection is created, an HTTP request is used to upgrade the connection. Client │ HTTP Upgrade Request ▼ Server │ 101 Switching Protocols ▼ WebSocket Connection Communication Flow Client │ Connect ▼ Socket.IO Server │ Connection ▼ Exchange Messages │ Disconnect WebSocket vs Socket.IO Feature WebSocket Socket.IO Type Protocol Library Real-Time ✅ Yes ✅ Yes Auto Reconnect ❌ No ✅ Yes Rooms ❌ Manual ✅ Built-in Broadcasting ❌ Manual ✅ Built-in Event API Basic Rich Event-Based API Fallback Transport ❌ No ✅ Yes Ease of Use Lower-level Easier Socket.IO Events Method Purpose connection Client connected disconnect Client disconnected emit() Send event on() Listen for event join() Join room leave() Leave room Request Flow Browser │ Connect ▼ Socket.IO Server │ Message ▼ Database │ Response ▼ Browser Real-Life Example 💬 Online Chat User A │ Hello ▼ Server │ ▼ User B Instant Message Applications Application Use WhatsApp Chat Facebook Notifications Uber Live Location Online Games Multiplayer Trading Apps Live Prices Cricket Apps Live Scores Interview Question What is WebSocket? Answer WebSocket is a protocol that provides a persistent, two-way communication channel between the client and the server. What is Socket.IO? Answer Socket.IO is a JavaScript library that simplifies real-time communication by providing features such as automatic reconnection, rooms, namespaces, and event-based messaging. What is the main difference between WebSocket and Socket.IO? Answer WebSocket is a communication protocol. Socket.IO is a library that often uses WebSocket underneath while adding extra features. Which event is triggered when a client connects? Answer connection Which method sends a message to all clients? Answer io . emit() Best Practices ✅ Use Socket.IO when you need features like rooms, reconnection, and broadcasting. ✅ Authenticate users before establishing socket connections. ✅ Validate all incoming messages. ✅ Handle disconnect and reconnect events. ✅ Use rooms for private chats and group communication. ✅ Scale Socket.IO with a shared adapter (such as Redis) when using multiple server instances. ❌ Don't trust data sent by the client. ❌ Don't leave unused socket connections open. Key Points ✅ WebSocket is a protocol for persistent two-way communication. ✅ Socket.IO is a library built on top of WebSocket concepts with additional features. ✅ WebSockets provide low-latency communication. ✅ Socket.IO supports automatic reconnection, rooms, namespaces, and broadcasting. ✅ socket.emit() sends to one client. ✅ io.emit() sends to all connected clients. ✅ WebSockets are widely used for chat, live notifications, games, and live tracking. 🧠 Easy Formula Client │ ▼ WebSocket Connection │ ▼ Socket.IO │ ▼ Events │ ▼ Real-Time Communication WebSocket = Protocol Socket.IO = Library socket.on() = Listen Event socket.emit() = Send Event io.emit() = Send to Everyone socket.join() = Join Room io.to(room).emit() = Send to Room Remember: 🔌 WebSocket = Persistent two-way communication protocol ⚡ Socket.IO = Real-time library with extra features 💬 socket.emit() = Send to one client 🌍 io.emit() = Send to all connected clients 👥 Rooms = Group messaging 🚀 Perfect for chat applications, live notifications, multiplayer games, and real-time dashboards