Real-Time Communication

Compare polling, server-sent events, WebSockets, and WebRTC for live applications.

Lesson content

🎯 Goal By the end of this lesson, you'll understand: What is Real-Time Communication? Why do we need it? Polling vs WebSockets What is Socket.IO? How Real-Time Communication works Express + Socket.IO example Real-world examples Interview questions What is Real-Time Communication? Real-Time Communication allows the server and client to exchange data instantly without the user refreshing the page. Simple Definition: Real-Time Communication means data is sent and received immediately. Why Do We Need Real-Time Communication? It is used for: Chat Applications Live Notifications Live Stock Prices Online Games Food Delivery Tracking Video Calls Live Sports Scores Real-Life Example 💬 Imagine chatting on WhatsApp. You Send Message │ ▼ Server │ ▼ Friend Receives Immediately No page refresh is needed. Traditional HTTP Communication Browser │ Request ▼ Server │ Response ▼ Browser If new data arrives, the browser must send another request. Real-Time Communication Browser │ ▼ WebSocket Connection ▲ │ Server The connection stays open, allowing both sides to send data anytime. Polling vs WebSockets Polling Client │ Request ▼ Server Every 5 Seconds Example: "Any new message?" "Any notification?" "Any update?" Even if nothing has changed, requests continue. WebSocket Client ▲ │ Permanent Connection │ ▼ Server The server pushes updates immediately. Polling vs WebSocket Feature Polling WebSocket Connection New request each time Single persistent connection Speed Slower Faster Network Usage Higher Lower Real-Time Limited Excellent Suitable For Simple updates Chat, Games, Live Apps What is Socket.IO? Socket.IO is a library that makes real-time communication easy in Node.js. It works with: Node.js Express Browser Mobile Apps Simple Definition: Socket.IO helps clients and servers exchange messages instantly. Install Socket.IO npm install socket.io Install 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 Client Connection io . on( "connection" , ( socket ) => { console . log( "User Connected" ); }); Output User Connected Send Message to Client io . on( "connection" , ( socket ) => { socket . emit( "message" , "Welcome User" ); }); Receive Message io . on( "connection" , ( socket ) => { socket . on( "chat" , ( message ) => { console . log( message ); }); }); Output Hello Server Broadcast Message Send a message to all connected clients except the sender . socket . broadcast . emit( "message" , "New User Joined" ); Send to All Clients io . emit( "notification" , "Server Restarting" ); Every connected client receives the notification. Disconnect Event socket . on( "disconnect" , () => { console . log( "User Disconnected" ); }); Complete Flow Client Connects │ ▼ Socket.IO Server │ ▼ Connection Established │ ▼ Send & Receive Messages │ ▼ Disconnect Chat Application Flow User A │ Hello ▼ Server │ ▼ User B Message Delivered Instantly Rooms Rooms allow grouping users. Example: socket . join( "room1" ); Send message to room: io . to( "room1" ) . emit( "message" , "Hello Room" ); Namespaces Namespaces separate communication channels. const admin = io . of( "/admin" ); Clients connecting to /admin only receive admin events. Acknowledgements The client can receive confirmation that the server processed an event. socket . on( "save" , ( data , callback ) => { callback ( "Saved Successfully" ); }); Request Flow User │ ▼ Socket.IO Connection │ ▼ Server │ ▼ Database │ ▼ Instant Response Real-Life Example 🚖 Ride Booking App Driver Location │ ▼ Server │ ▼ Passenger Map Updates Every Second Common Use Cases Application Real-Time Feature WhatsApp Chat Messages Facebook Notifications Uber Live Driver Location Cricket App Live Score Online Games Player Updates Trading App Live Stock Prices Socket.IO vs WebSocket Feature Socket.IO WebSocket Protocol Uses WebSocket when available and can fall back to other transports WebSocket Protocol Auto Reconnect ✅ Yes ❌ Manual Implementation Rooms ✅ Yes ❌ No (implement yourself) Broadcasting ✅ Built-in ❌ Manual Event-Based API ✅ Yes ❌ Manual Ease of Use Easy Lower-level API Interview Question What is Real-Time Communication? Answer Real-Time Communication allows clients and servers to exchange data instantly without refreshing the page. What is Socket.IO? Answer Socket.IO is a Node.js library that enables event-based real-time communication between clients and servers. What is the difference between Polling and WebSocket? Answer Polling: Client repeatedly sends requests to check for updates. WebSocket: A persistent connection allows instant two-way communication. What is socket.emit() ? Answer It sends an event and data to a specific connected client. What is io.emit() ? Answer It sends an event and data to all connected clients . Best Practices ✅ Use WebSockets or Socket.IO for real-time features. ✅ Authenticate users before allowing socket connections. ✅ Handle disconnect and reconnect events gracefully. ✅ Validate incoming messages from clients. ✅ Use rooms for chat groups and private channels. ✅ Scale Socket.IO with a shared adapter (such as Redis) when running multiple server instances. ❌ Don't trust client-sent data without validation. ❌ Don't keep unnecessary socket connections open. Key Points ✅ Real-Time Communication provides instant data exchange. ✅ WebSockets maintain a persistent connection. ✅ Socket.IO simplifies real-time communication in Node.js. ✅ socket.emit() sends to one client. ✅ io.emit() sends to all connected clients. ✅ Rooms and namespaces help organize communication. ✅ Handle disconnects and reconnections properly. 🧠 Easy Formula Client Connect │ ▼ Socket.IO Server │ ▼ Connection Established │ ▼ Send Events │ ▼ Receive Events │ ▼ Disconnect Socket.IO = Real-Time Communication socket.emit() = One Client io.emit() = All Clients socket.join() = Join Room io.to(room).emit() = Send to Room socket.on() = Listen for Events Remember: ⚡ Real-Time = Instant communication 🔌 WebSocket = Persistent two-way connection 💬 Socket.IO = Easy real-time library for Node.js 📡 socket.emit() = Send to one client 🌍 io.emit() = Send to all clients 👥 Rooms = Group communication 🚀 Ideal for chat apps, notifications, live tracking, online games, and live dashboards