Consider an Express server using WebSocket for real-time chat. When a client sends a new message, what does the server do to update all connected clients immediately?
const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); wss.on('connection', ws => { ws.on('message', message => { // What should happen here? }); }); server.listen(3000);
Think about how real-time communication works to keep all users updated instantly.
In real-time applications, the server broadcasts messages immediately to all connected clients to keep everyone in sync without delay.
Look at the following Express and WebSocket server code. Which option correctly identifies the syntax error?
const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); wss.on('connection', ws => { ws.on('message', message => { wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(message) } }); }); }); server.listen(3000);
Check each line carefully for punctuation errors.
JavaScript requires semicolons or line breaks to separate statements. Missing semicolon after client.send(message) can cause issues.
In an Express WebSocket server, after broadcasting a message to all clients, what is the state of the clients that received the message?
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send('Hello');
}
});Think about how WebSocket connections behave during message sending.
Clients stay connected after receiving messages unless explicitly disconnected. Sending messages does not pause or disconnect clients.
Given this code, why do clients not receive broadcast messages?
const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); wss.on('connection', ws => { ws.on('message', message => { wss.clients.forEach(client => { if (client.readyState === WebSocket.CLOSED) { client.send(message); } }); }); }); server.listen(3000);
Check the condition inside the forEach loop carefully.
Clients must be in OPEN state to receive messages. Checking for CLOSED means no client matches the condition.
Which of the following best explains why real-time communication is important in Express applications?
Think about how apps like chat or live sports updates work.
Real-time communication lets servers send data instantly without waiting for client requests, making apps feel fast and interactive.