WebSocket is often chosen over HTTP for certain applications. What is the main advantage of using WebSocket compared to HTTP?
Think about how data flows between client and server in real-time apps like chat.
WebSocket enables full-duplex communication, meaning both client and server can send messages independently at any time. HTTP is request-response only.
In a Node.js WebSocket server, what happens immediately after a client sends a message?
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { ws.on('message', message => { // What happens here? }); });
Consider the event listeners set up on the server side.
When a client sends a message, the server's 'message' event handler runs immediately, allowing the server to handle or reply to the message.
Which of the following code snippets correctly sends a text message 'Hello' to a connected WebSocket client?
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { // send message here });
Check the official WebSocket API method for sending data.
The correct method to send data to a WebSocket client is send(). Other methods do not exist or do not send messages.
Consider this Node.js WebSocket server code. Why does it never send a response back to clients?
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { ws.on('message', message => { ws.sendMessage('Received: ' + message); }); });
Check the WebSocket API method names carefully.
The WebSocket client object has a send() method, not sendMessage(). Using a wrong method causes no message to be sent.
Given the following Node.js WebSocket server code, what is the value of count after three messages are received from any clients?
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); let count = 0; wss.on('connection', ws => { ws.on('message', message => { count += 1; ws.send(`Message number ${count}`); }); });
Count increases each time any client sends a message.
The variable count is incremented every time any client sends a message. After three messages total, count is 3.