Lessons available in both languages
MERN Stack · Interview Prep

Socket.io & WebSockets interview questions & answers

174+ real Socket.io & WebSockets interview questions with model answers, plus free lessons to learn the concepts. Prepare in English & Hinglish, then practise with an AI mock interview.

18 topics · 174+ questions

Hirenix kaise padhata hai

Ek chapter. 90 minute.
Interview ke liye taiyaar.

Har concept ek real-world problem se — jaisa production code mein aata hai, waisa. Ratna nahi padta, samajh aa jaata hai. Har question ka model answer diya hai: interviewer ko exactly kya bolna hai, aur kyun. Phir usi chapter ka AI mock interview.

  • 📖Concept, 5 min meinJargon nahi — seedhi baat
  • 🛠️Real-world problemJaisa production code mein aata hai
  • 💬Model answerInterview mein kya bolna hai
  • 🧠FlashcardsRevision 10 min mein
  • 🤖AI mock interviewFollow-up bhi poochta hai
  • 📊Weak topicsKahan phans rahe ho, pata chale
Ye chapter shuru karo — free🌐 English🇮🇳 Hinglish
A student learning an interview concept on Hirenix at home
Video playlistsyllabus ke hisaab se18h+
Hirenix chapterinterview ke hisaab se90 min

Farq content ka nahi, filter ka hai — sirf wahi jo production mein actually use hota hai aur interview mein actually poocha jaata hai. Kitaabi topics jo industry mein kahin nahi chalte, wo yahan nahi milenge.

Lessons available in both languages

What you’ll learn

  • Real-time kya hai?
  • HTTP vs WebSocket
  • WebSocket API basicsFree account
  • Socket.io kya hai?Free account
  • Server setupFree account
  • Client setupFree account
  • Events: emit & onFree account
  • AcknowledgementsFree account
  • BroadcastingFree account
  • RoomsFree account
  • NamespacesFree account
  • Connection lifecycleFree account
  • Express integrationFree account
  • Auth & securityFree account
  • Scaling & recapFree account
  • Project 1: Real-time chat app
  • Project 2: Live notificationsFree account
  • Project 3: Typing indicator & presenceFree account

Real-time kya hai?

Normal HTTP chitthi bhejne jaisa hai: tum request likhte ho, post karte ho, aur reply ka wait karte ho. Jab tak tum na pucho, kuch move nahi hota. Latest score jaanna hai to ANOTHER chitthi likhni padegi aur dobara check karna padega. Real-time ek open phone call jaisa hai: jaise hi kuch hota hai, koi bhi side bol sakti hai — pehle 'poochna' nahi padta.

Request-response (HTTP) me, server passive hota hai — wo sirf client ki bheji hui request ka reply de sakta hai. Uske paas khud se data push karne ka koi tareeka nahi. Ye page load ya form submit ke liye theek hai, par jo cheez bina user ke pooche change hoti hai uske liye kaam nahi karta: koi doosre ne bheja chat message, ek live cricket score, ek notification ('kisi ne tumhari post like ki'), presence ('friend abhi online aaya'), ya collaborative editing (shared doc me teammate ka cursor move hota dekhna, jaise Google Docs). In sabme SERVER ko jaise hi kuch hota hai turant push karna padta hai — agli request ka wait nahi kar sakta.

WebSocket aane se pehle, devs do workarounds se real-time fake karte the:

  • Polling: client har kuch second me poochta hai "kuch naya hai?" (setInterval + fetch). Simple, par wasteful (zyada jawab "nahi" hote hain) aur laggy (us interval jitni delay).
  • Long-polling: client ek baar poochta hai, par server request ko OPEN HOLD karta hai aur sirf tab respond karta hai jab naya data ho (ya timeout) — phir client turant dobara poochta hai. Polling se kam wasteful, par phir bhi andar se request-response par based, har cycle me connection overhead ke saath.
  • WebSocket: ek hi connection OPEN raha hai, aur koi bhi side jab chaho turant data bhej sakti hai — poochna nahi, reconnect nahi karna. Ye asli fix hai, aur Socket.io isi ke upar bana hai (agle topics me isko wire karenge).

🌍 Real-world example: WhatsApp Web par naya message tumhare friend ke bhejte hi SECOND me dikh jaata hai — koi refresh nahi, koi noticeable polling delay nahi. Ye tabhi possible hai kyunki server ek open connection par push karta hai, na ki tumhara browser baar-baar dobara pooch raha hai.

💡 push = server khud se client ko data bhejta hai, client ke pooche bina.

💡 polling = client ek timer par baar-baar poochta hai "kuch naya hai?" — wasteful aur laggy.

💡 long-polling = client ek baar poochta hai, server request ko open hold karta hai jab tak data na ho — polling se behtar, par phir bhi request-based.

Yahan ek chhota teaser hai ki "asli" real-time code kaisa dikhta hai — ek client jo persistent connection kholta hai aur server ke pushes sunta hai (poora setup baad ke topics me aayega):

Standard definition: Real-time means the server can push data to the client the instant something happens, instead of the client having to repeatedly ask (HTTP request-response) — needed for chat, live scores, notifications, presence, and collaborative editing; achieved today with WebSocket (and libraries like Socket.io built on top of it), after earlier workarounds like polling and long-polling.

// client — a first look at a persistent connection (Socket.io, covered in depth soon)
import { io } from 'socket.io-client';

const socket = io('http://localhost:3000');

socket.on('connect', () => {
  console.log('connected:', socket.id);
});

socket.on('chat message', (msg) => {
  console.log('server pushed:', msg); // arrives instantly, no request needed
});

HTTP vs WebSocket

HTTP ko socho letters bhejna jaisa. Tum ek letter likhte ho (request), post karte ho, aur reply ka wait karte ho (response). Postman kabhi bell nahi bajata koi letter dene ke liye jo tumne maanga hi nahi tha — client ko hamesha pehle ASK karna padta hai. Ab WebSocket ko socho ek open phone call jaisa. Ek baar call connect ho jaaye, to koi bhi banda kabhi bhi bol sakta hai — kisi ko bolne ke liye "permission maangni" nahi padti. Yahi core difference hai: HTTP request-response hai, WebSocket persistent aur full-duplex hai.

HTTP me, har request ek connection kholti hai, ek response milta hai, aur (typically) band ho jaata hai. Server KABHI khud se data push nahi kar sakta — agar client nahi maangega, to usko update nahi milega. Ye page load ke liye theek hai, par live chat ya live score ke liye bekaar hai jo bina refresh kiye badalta hai.

WebSocket me, ek baar ka handshake hota hai: client ek normal HTTP request bhejta hai jisme Upgrade: websocket header hota hai, aur agar server maan jaaye, to wo 101 Switching Protocols reply karta hai. Us ek handshake ke baad, WAHI underlying TCP connection open rehta hai — ab wo HTTP nahi raha, dono side ab ek doosre ko kabhi bhi message bhej sakte hain, kisi bhi direction me, low overhead ke saath (har message par headers repeat nahi hote, HTTP ke ulat jahan har request cookies/headers dobara bhejti hai).

🌍 Real-world example: Ek live chat app. Plain HTTP ke saath tumhe har kuch second me poochna padta "koi naya message hai?" (wasteful, laggy). WebSocket ke saath, server naya message aate hi seedha push kar deta hai — poochne ki zaroorat nahi.

💡 full-duplex = dono side ek saath bhej AUR receive kar sakte hain, phone call jaisa (HTTP ke ulat jo walkie-talkie jaisa hai: ek side bolta hai, ruk ke wait karta hai, doosra reply karta hai).

💡 handshake = ek-baar ka HTTP Upgrade request + 101 Switching Protocols response jo ek normal HTTP connection ko WebSocket connection me convert karta hai.

💡 ws:// vs wss:// = WebSocket ka URL scheme; ws:// plain hai (jaise http://), wss:// TLS ke upar encrypted hai (jaise https://) — production me hamesha wss:// use karo.

⚠ Gotcha: handshake koi alag protocol nahi hai jo scratch se bana ho — ye ek normal HTTP request ke upar chalta hai. Agar koi proxy/firewall Upgrade header ko block kar de ya 101 Switching Protocols support na kare, to WebSocket connection silently fail ho jaata hai ya fallback hota hai — yahi wo infra issue hai jiske liye Socket.io ka fallback mechanism exist karta hai.

Kab konsa use karo: WebSocket REST/CRUD ka replacement NAHI hai. Normal request-response kaam ke liye — user profile fetch karna, order create karna, form submit karna — plain HTTP simpler hai, cacheable hai, aur stateless hai, to usi se kaam chalao. WebSocket sirf tab lo jab tumhe continuous, bidirectional push chahiye: chat, live scores, notifications, collaborative editing, presence.

Standard definition: WebSocket is a protocol that upgrades a single HTTP connection (via an Upgrade request answered with 101 Switching Protocols) into a persistent, full-duplex connection where both client and server can send messages at any time with low overhead — unlike HTTP's request-response model where only the client can initiate.

// ---------- Client: raw WebSocket connection kholna ----------
const ws = new WebSocket('wss://example.com/socket'); // wss:// = encrypted (TLS)

ws.onopen = () => {
  console.log('Handshake done — connection is now persistent & full-duplex');
  ws.send('hello server');            // client kabhi bhi push kar sakta hai, poochne ki zaroorat nahi
};

ws.onmessage = (event) => {
  console.log('Server pushed:', event.data); // server bhi kabhi bhi push kar sakta hai
};

// ---------- Compare: HTTP — client ko hamesha poochna padta hai ----------
// fetch('https://example.com/messages')   // ek request -> ek response, phir band
//   .then(res => res.json())
//   .then(data => console.log(data));      // server ye khud se kabhi nahi bhej sakta

Project 1: Real-time chat app

Kya bana rahe hain: Ek real-time chat app end-to-end — ek Express server jo same port pe Socket.io bhi chalata hai, ek browser client jo connect hota hai, aur messages jo sabko INSTANTLY broadcast hote hain (no refresh, no polling). Ye real-time ke liye THE resume project hai — yahi wo hai jo interviewers tumse walk-through karwate hain: "ek message tumhare browser se sabke screen tak kaise pahunchta hai?"

Ant tak tum ek message ki poori journey trace kar paoge: user type karta hai → client socket.emit → server socket.on use receive karta hai → server io.emit (ya io.to(room).emit) use broadcast karta hai → har connected client ka socket.on fire hota hai → UI naya message render karta hai. Ye loop pakka aa gaya, to tum real-time architecture samajhte ho, sirf Socket.io syntax nahi.

🌍 Real-world example: Ye bilkul WhatsApp Web / Slack / Discord ka core loop hai. Tum ek message bhejte ho, wo tumhari khud ki screen pe AUR us conversation ke har dusre khule tab/device pe — instantly, bina kisi ke refresh kiye, dikhta hai. Hamare in-memory rooms ko ek database-backed room list se badal do aur ye production hai.

💡 Broadcast = ek message, server dwara bahut saare clients ko ek saath bheja gaya. Yahi to plain HTTP ke upar Socket.io ka poora point hai — server bina pooche PUSH kar sakta hai.


Step 0 — Mental model (pehle ye padho)

Ek normal Express route har HTTP request pe ek baar chalta hai aur khatam ho jaata hai. Chat app ko ulta chahiye: ek connection jo OPEN RAHE taaki server kisi bhi pal ek client ko message push kar sake, chahe wo client ne kuch pucha ho ya nahi. Yahi Socket.io hume deta hai — har browser tab ke liye ek persistent connection, jo Express ke SAME http server ke upar rehta hai.

Skeleton mein bilkul teen chalte hue parts hain:

  1. Ek shared server — Express normal routes handle karta hai, Socket.io real-time channel handle karta hai, dono same port pe.
  2. Server-side event wiringio.on('connection', socket => ...) har connecting client pe ek baar fire hota hai; uske andar hum socket.on('chat message', ...) sunte hain.
  3. Client-side event wiring — connect karo, socket.emit se bhejo, socket.on se receive karke render karo.

Jo bhi feature hum add karte hain (username, rooms), wo bas usi emit/on wiring pe SAWARI KARTA MORE DATA hai — skeleton kabhi nahi badalta.


Step 1 — Ek shared http server (Express + Socket.io ek port pe)

Socket.io ko attach karne ke liye ek raw Node http.Server chahiye — seedhe Express app object pe nahi. To hum khud http server banate hain aur use DONO ko de dete hain:

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
app.use(express.static('public')); // index.html + client.js serve karta hai

const server = http.createServer(app);          // EK server
const io = new Server(server, {                  // Socket.io isse attach hota hai
  cors: { origin: '*' }
});

server.listen(3000, () => console.log('Chat server on http://localhost:3000'));

Ho ye raha hai:

  1. http.createServer(app) hamare Express app ko ek raw Node http server mein wrap karta hai — sirf Express ko Socket.io ke haath nahi diya ja sakta, par ye wrapped server object diya ja sakta hai.
  2. new Server(server, {...}) Socket.io ko usi SAME server pe attach karta hai. Ab ek port (3000) DONO answer karta hai — normal HTTP requests (Express routes, static files) AUR WebSocket upgrade handshake (Socket.io).
  3. Hum server.listen(...) karte hain, app.listen(...) NAHI — app.listen apna alag http server bana deta jise Socket.io kabhi dekhta hi nahi.
  4. cors: { origin: '*' } browser client ko (jo dev ke dauran alag origin se serve ho sakta hai) connect karne deta hai.

💡 Ye #1 gotcha hai jo interviewers check karte hain: agar tum app.listen() karte ho aur alag se io ko app pe attach karne ki koshish karte ho, to port share hona chupke se fail ho jaata hai. Socket.io ko http.Server pe attach hona HI CHAHIYE, aur Express ko http.createServer() mein diya gaya request handler hona CHAHIYE.


Step 2 — Server: io.on('connection') + socket.on('chat message') → io.emit

Ye poore app ka dil hai — wo server-side wiring jo ek aane wale message ko sabke liye broadcast bana deti hai:

io.on('connection', (socket) => {
  console.log('a user connected:', socket.id);

  socket.on('chat message', (msg) => {
    console.log('message:', msg);
    io.emit('chat message', msg);   // HAR connected client ko bhejo, sender samet
  });

  socket.on('disconnect', () => {
    console.log('user disconnected:', socket.id);
  });
});

Ho ye raha hai:

  1. io.on('connection', socket => ...) — Socket.io ye callback har connect hone wale browser tab ke liye EK BAAR call karta hai. socket us EK client ka private channel hai; io (neeche use hota hai) matlab SAARE clients.
  2. Uske andar, socket.on('chat message', msg => ...) ek custom event sunta hai jiska naam 'chat message' hai — ye naam arbitrary hai, HUM ne chuna hai, aur client ko exact wahi string emit karna padega.
  3. Jab ek message aata hai, io.emit('chat message', msg) use HAR connected socket ko wapas broadcast karta hai (jisne bheja tha use samet) — isi liye sender ko bhi apna khud ka message dikhta hai, baaki sabki tarah.
  4. socket.on('disconnect', ...) fire hota hai jab wo tab band hota hai ya connection toot jaata hai — cleanup ke liye achhi jagah (baad mein presence ke liye use karenge).

💡 socket.on vs io.on: io.on('connection', ...) har client ke liye EK-BAAR setup hai. socket.on('chat message', ...) us ek client ke channel pe PER-EVENT listener hai. io.emit sabko pahunchta hai; socket.emit sirf usi sender ko reply karta.


Step 3 — Client: connect, submit pe bhejo, incoming render karo

Browser side pe (plain JS ya React useEffect ke andar — wiring wahi hai):

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();   // usi server se connect hota hai jisne page serve kiya

  const form = document.getElementById('form');
  const input = document.getElementById('input');
  const messages = document.getElementById('messages');

  form.addEventListener('submit', (e) => {
    e.preventDefault();
    if (input.value) {
      socket.emit('chat message', input.value);   // BHEJO
      input.value = '';
    }
  });

  socket.on('chat message', (msg) => {              // RECEIVE
    const item = document.createElement('li');
    item.textContent = msg;
    messages.appendChild(item);
  });
</script>

Ho ye raha hai:

  1. Bina arguments ke io() wapas usi host se connect hota hai jisne page serve kiya — Socket.io ka client script (server dwara /socket.io/socket.io.js pe auto-serve hota hai) ise available banata hai.
  2. Form submit pe hum preventDefault() karte hain (page reload nahi) aur socket.emit('chat message', input.value) — ye bilkul wahi string hai jo server ka socket.on('chat message', ...) sun raha hai.
  3. socket.on('chat message', msg => ...) client ka APNA listener hai — ye server ke bheje har broadcast pe fire hota hai, isi client se aaye messages ke liye bhi (kyunki server ne io.emit use kiya, socket.broadcast.emit nahi).
  4. Rendering bas DOM manipulation hai: har aane wale message ke liye ek naya <li> append karo. React mein ye setMessages(prev => [...prev, msg]) hoga usi socket.on callback ke andar, ek useEffect mein register hokar unmount pe socket.off('chat message', handler) cleanup ke saath.

💡 Same event name, dono directions. Client 'chat message' emit karta hai AUR 'chat message' sunta bhi hai — ye normal hai; server hi wo hai jo use sabko wapas relay karta hai, sender samet.


⭐ Step 3.5 — Ek message ko end-to-end TRACE karo

EK message ko poore system se follow karo, beat by beat. Maano user Aisha "hi everyone" type karti hai aur Enter dabati hai, Bilal ka browser bhi connected hai:

  1. Aisha ka browser: form submit fire hota hai → socket.emit('chat message', 'hi everyone') Aisha ke APNE socket connection se string ko server tak bhejta hai.
  2. Server use receive karta hai: Aisha ke socket pe register socket.on('chat message', msg => ...) callback (uske io.on('connection', ...) block ke andar) msg = 'hi everyone' ke saath fire hota hai.
  3. Server rebroadcast karta hai: us handler ke andar, io.emit('chat message', msg) chalta hai — ye HAR connected client ke socket tak pahunchta hai, sirf Aisha ke tak nahi.
  4. Aisha ke browser ko wapas milta hai: uska apna socket.on('chat message', ...) listener 'hi everyone' ke saath fire hota hai — use apna khud ka message list mein dikhta hai (ye io.emit ka behavior hai — sender ko include karta hai).
  5. Bilal ke browser ko milta hai: uska socket.on('chat message', ...) listener BHI wahi 'hi everyone' ke saath fire hota hai, kyunki wo ek connected socket hai aur io.emit un sabtak pahunchta hai.
  6. Dono UIs update hote hain: har browser ka listener callback apna document.createElement('li') (ya setMessages) chalata hai — to Aisha aur Bilal dono ko unki message list mein "hi everyone" dikhta hai, lagbhag usi pal, bina page reload aur bina kisi ke poll kiye.

Jo one-way HTTP request ye sab shuru karti hai (initial page load), wo bahut pehle khatam ho chuki hoti hai. Uske baad sab kuch — Aisha ka message Bilal tak pahunchna — wahi STILL-OPEN Socket.io connection pe travel karta hai. Yahi persistent connection hi iske instant lagne ki poori wajah hai.


Step 4 — Ek USERNAME add karo

Abhi har message anonymous hai. Hum payload mein ek username jodte hain, ya to ek login prompt se ya ek simple form field se:

// client: bare string ki jagah { user, text } bhejo
socket.emit('chat message', { user: username, text: input.value });

// client: dono render karo
socket.on('chat message', (msg) => {
  const item = document.createElement('li');
  item.textContent = `${msg.user}: ${msg.text}`;
  messages.appendChild(item);
});

// server: wiring unchanged, bas payload jo bhi shape ho relay kar do
socket.on('chat message', (msg) => {
  io.emit('chat message', msg);   // { user, text } seedha nikal jaata hai
});

Ho ye raha hai: event ka naam ('chat message') aur emit→on wiring BILKUL wahi rehte hain — humne bas payload ko plain string se ek object { user, text } mein badla. Socket.io objects ko automatically JSON ki tarah serialize kar deta hai, koi extra kaam nahi. Server ko ye jaanne ki zaroorat bhi nahi ki shape badla — wo bas jo bhi mila use relay kar raha hai. Ye pattern hai baad mein KOI BHI naya field add karne ke liye (timestamp, avatar, message id): payload object ko badhao, wiring ko nahi.

💡 Zyada secure version connection time pe server pe username store karta hai (socket.data.username = name) taaki client payload mein kisi aur ka naam spoof na kar sake — interviews mein production-grade version ki tarah mention karne layak.


Step 5 — ROOMS add karo (room join karo, broadcasts scope karo)

Abhi io.emit HAR connected client ko bhejta hai — ek global chat ke liye theek, multiple rooms wale chat app ke liye galat. socket.join(room) ek socket ko ek named room mein daalta hai; io.to(room).emit(...) SIRF us room ke sockets ko bhejta hai:

// client: connect hone ke baad room join karo
socket.emit('join room', roomName);

// client: us room context ke andar bhejo
socket.emit('chat message', { room: roomName, user: username, text: input.value });

// server: join + scoped broadcast
io.on('connection', (socket) => {
  socket.on('join room', (room) => {
    socket.join(room);
    console.log(`${socket.id} joined room ${room}`);
  });

  socket.on('chat message', (msg) => {
    io.to(msg.room).emit('chat message', msg);   // SIRF msg.room ke sockets ko milta hai
  });

  socket.on('disconnect', () => {
    console.log('user disconnected:', socket.id);
  });
});

Ho ye raha hai:

  1. socket.join(room) ek SERVER-side call hai — client bas 'join room' event room ke naam ke saath emit karta hai; server hi wo hai jo actually us socket ko room mein add karta hai. Rooms client ko invisible hote hain — ye bookkeeping Socket.io internally per socket rakhta hai.
  2. io.to(room).emit(event, data) io.emit ka scoped cousin hai — globally har socket tak pahunchne ki jagah, ye sirf un sockets tak pahunchta hai jinhone us exact room ke naam ke liye socket.join(room) call kiya.
  3. Ab hum har message ko msg.room se tag karte hain taaki server ko pata chale KIS room mein broadcast karna hai — client ise apne emit payload mein include karta hai.
  4. Ek socket ek saath multiple rooms mein ho sakta hai, aur socket.leave(room) se chhod sakta hai (jaise room switch karte waqt) — warna wo chupke se un rooms se messages receive karta rahega jo visually chhod chuka hai.

💡 io.emit vs io.to(room).emit: io.emit = server pe sab, bina kisi exception ke. io.to(room).emit = sirf wo sockets jinhone us room ko join kiya. Global chat → per-room chat badalna bas io.emit ko io.to(msg.room).emit se replace karna hai plus join room step — Step 2/3 wala emit→on skeleton bilkul nahi badalta.


🔎 Poora flow (wiring ka recap)

Har chat message wahi BEAT follow karta hai, room-scoped ho ya na ho:

  1. Client emit karta haisocket.emit('chat message', payload) isi client ke apne connection se upar bhejta hai.
  2. Server ka socket.on use receive karta haiio.on('connection', socket => ...) ke andar, har connected client ke liye ek listener.
  3. Server rebroadcast karta haiio.emit(...) (sabko) ya io.to(room).emit(...) (sirf us room ko).
  4. Har target client ka socket.on fire hota hai — original sender ka bhi, kyunki broadcasts default se exclude nahi karte.
  5. Har client render karta hai — listener callback DOM (ya React state) ko naye message ke saath update karta hai.

Aur wiring shape kabhi nahi badalta jaise-jaise tum features add karte ho — username aur room bas usi 'chat message' emit/on pair pe sawaar MORE FIELDS hain usi payload object mein.


🚀 Ye aage kahan jaata hai

Ye skeleton — shared server, io.on('connection'), socket.on/io.emit, rooms — HAR real-time feature ka base hai: typing indicators (socket.to(room).emit('typing', ...), sender ko exclude karke), online presence (connect/disconnect pe sockets track karo), read receipts, live notifications. Tum poora pattern pehle se jaante ho; bas event ka naam aur payload shape badalta hai.


✅ Jo tumne abhi seekha

  • Ek shared http server Express + Socket.io ke liye — http.createServer(app) phir new Server(server, {...}), aur server.listen(...) app.listen(...) NAHI.
  • io.on('connection') har client pe fire hota hai; uske andar, socket.on('chat message', ...) us client ke messages sunta hai.
  • io.emit sabko broadcast karta hai (sender samet) — ye mechanism hai jo chat ko har khule tab ke liye instant banata hai.
  • Client wiring — submit pe bhejne ke liye socket.emit, receive karke render karne ke liye socket.on, dono directions mein same event name.
  • Ek message trace karna end-to-end: client emit → server socket.on → server io.emit/io.to → har target client ka socket.on → UI render.
  • Payload badhao, wiring nahi — username add karna bas bare string ki jagah { user, text } hai.
  • Roomssocket.join(room) (server-side) + io.to(room).emit(...) broadcasts ko sirf us room ke sockets tak scope karta hai.
// server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
app.use(express.static('public'));

const server = http.createServer(app);
const io = new Server(server, { cors: { origin: '*' } });

io.on('connection', (socket) => {
  console.log('a user connected:', socket.id);

  socket.on('join room', (room) => {
    socket.join(room);
  });

  socket.on('chat message', (msg) => {
    // msg = { room, user, text }
    if (msg.room) {
      io.to(msg.room).emit('chat message', msg);
    } else {
      io.emit('chat message', msg); // global fallback
    }
  });

  socket.on('disconnect', () => {
    console.log('user disconnected:', socket.id);
  });
});

server.listen(3000, () => console.log('Chat server on http://localhost:3000'));

// public/client.js (or a React useEffect)
const socket = io();
const username = prompt('Your name?') || 'Anonymous';
const room = 'general';
socket.emit('join room', room);

form.addEventListener('submit', (e) => {
  e.preventDefault();
  if (input.value) {
    socket.emit('chat message', { room, user: username, text: input.value });
    input.value = '';
  }
});

socket.on('chat message', (msg) => {
  const item = document.createElement('li');
  item.textContent = `${msg.user}: ${msg.text}`;
  messages.appendChild(item);
});

Socket.io & WebSocketsinterview questions & answers

10 sample questions below — 174+ in the full bank inside.

Socket.io me emit aur on me kya farq hai?

emit() ek named event bhejta hai ek taraf se doosre taraf; on() sunta hai aur us event ko receive karta hai. Agar server 'message' emit kare, to client ke paas socket.on('message') listener hona chahiye jisse receive kar sake. Ye dono ek pair me kaam karte hain — ek bhejta hai, doosra sunta hai.

In simple terms: Emit ko letter bhejne jaisa samjho aur on ko mailbox jaisa jo use pakdhe. Postman (emit) letter ko box (on) me dalta hai. Jaise: server 'notification' emit kare → sab clients jo socket.on('notification', (data) => console.log(data)) se sun rahe hain, data milega.

socket.emit() kya karti hai? Kaun se client ko message milta hai?

socket.emit() SIRF us ek specific client ko message bhejti hai jo event trigger kiya (dusre clients ko nahi). Use karo jab tum kisi ek user ko private response dena ho — jaise 'data save ho gaya' confirmation sirf us ek client ko.

In simple terms: socket.emit ko ek SMS samjho jo SIRF ek phone ko jaata hai (sender ko hi milta hai). Jaise server 'save' event receive kare, kuch kaam kare, phir `socket.emit('save-confirm', { status: 'ok' })` sirf us ek client ko reply de.

Jab client Socket.io server se connect karta hai, kya hota hai?

Server ek 'connection' event fire karta hai, aur us socket object ko mil jata hai jo us client ko represent karta hai. Handler ke andar, tum us client se events sun sakte ho, use events bhej sakte ho, ya use rooms me add kar sakte ho. Har ek connected client ka apna socket instance hota hai.

In simple terms: Isko waiter ka customer se greeting maano jab wo table par baithe. Table (socket) ab us customer ke liye 'reserved' hai; waiter ko pata hai kaunsa table ko serve karna hai. Example: io.on('connection', (socket) => { console.log('Client connected:', socket.id); }).

socket.id kya hota hai aur iska unique kyu hona zaroori hai?

socket.id Socket.io ki taraf se assign kiya gaya unique identifier hota hai har ek connected client ke liye. Ye automatically generate hota hai jab connection establish hoti hai aur usi server instance ke andar unique hota hai. Tum iska use ek specific client ko identify karne aur message bhejne ke liye karte ho.

In simple terms: Isko shop ka ticket number maano—har customer ko ek ticket milta hai jab wo enter karte hain taaki shop ko pata chale kise bulana hai. Example: agar socket.id = '12345abc' hai, tum sirf us client ko message bhej sakte ho io.to('12345abc').emit('message', data) se.

Socket.io code likho jahan client ek message bheje aur server use receive kare.

Client: socket.emit('chat message', { text: 'Hello' }); Server: socket.on('chat message', (data) => { console.log(data.text); });

In simple terms: Client emit use karta hai data bhejne ke liye custom event name 'chat message' ke saath. Server same event name pe on se sunta hai aur callback me data receive karta hai. Event name ek label jaisa kaam karta hai taki dono sides ko pata chale ye kaun sa message type hai.

Server-side code likho: event receive karo aur acknowledgement bhejo.

socket.on('save', (data, ack) => { console.log('Received:', data); // process the data const result = { success: true, id: 123 }; ack(result); // ack ko call karo response client ke paas bhejne ke liye }); Server listener ko DO args milte hain: `data` (jo client ne bheja) aur `ack` (callback function). `ack(response)` call karo response client ke callback ko bhejne ke liye.

In simple terms: Server pe `ack` wo callback hai jo client ne pass kiya. Jab tum `ack(result)` call karo, ye `result` directly client ke callback ko bhej deta hai. Jaisa: server package receive kare, process kare, form sign kare (ack call kare), aur confirmation back bheje — sab same WebSocket ke through.

Client-side se code likho: event emit karo WITH acknowledgement callback.

socket.emit('save', { name: 'John', age: 25 }, (ackResponse) => { console.log('Server responded:', ackResponse); if (ackResponse.success) { console.log('Data saved successfully'); } }); Callback (last arg) run hota hai jab server ack ko call kare. `ackResponse` mein server ka reply hota hai.

In simple terms: Callback tumhara 'mailbox' hai reply ke liye. Jab tum `socket.emit('event', data, callback)` se emit karo, tum server se request karte ho process aur respond karne ke liye. Jaise: user form submit kare, tum callback ke saath emit karo, server validate kare aur success/error ke saath back call kare. Ek request-response pair WebSocket ke through.

socket.emit() aur io.emit() me kya difference hai? Code likho.

`socket.emit('event', data)` SIRF us ek client ko message bhejta hai. `io.emit('event', data)` (server se) SAARE connected clients ko broadcast karta hai, sender included. Code: `io.emit('notification', { text: 'Server update' })` sabko reach karta hai.

In simple terms: socket.emit = ek person ko SMS; io.emit = sab ko announcement. Dono server se aata hai. Jaise naya user join kare, `io.emit('user-count', 5)` saab ko batata hai count update hua, lekin `socket.emit('welcome', {name})` sirf us naye user ko welcome bolti hai.

Socket.io mein acknowledgement (ack) kya hota hai?

Acknowledgement (ack) ek callback function hai jo `socket.emit()` ka LAST argument hota hai. Jab server ko event milta hai, wo is callback ko call karta hai confirm karne ke liye ya data return karne ke liye — jaisa request-response ek WebSocket ke andar.

In simple terms: Ack ko delivery confirmation samjho: tum letter bhejte ho (emit with callback) aur recipient signature karta hai confirm karne ke liye (server callback ko call karta hai). Jaise: `socket.emit('save', { data }, (response) => console.log('Saved!'));` Server receives, saves, aur callback ko result ke saath call karta hai.

Socket.io me teen built-in/reserved events batao jo custom event names ke liye use nahi kar sakte.

connect (jab client connect ho), disconnect (jab client disconnect ho), aur connect_error (jab connection error ho). Ye special Socket.io events hain jo automatically fire hote hain; tum inhe sunne ke liye on se listen karte ho par custom event names ke liye use nahi kar sakte.

In simple terms: Socket.io kuch event names apne liye reserve karta hai. Jab client connect hota hai, connect automatically fire hota hai. Jab client leave kare ya network down ho, disconnect fire hota hai. Agar auth fail ho, connect_error fire hota hai. Ye ghar ke kaam ke events hain, custom messages nahi — example: socket.on('connect', () => console.log('I am online')).

164+ more Socket.io & WebSockets questions inside

Create a free account to read the full question bank, learn every topic, and practise with an AI mock interview.

Unlock all questions — free

Ready to practise Socket.io & WebSockets?

Unlock every topic free, then face an AI interviewer that asks follow-ups and grades your answers.