WebSocket supports full-duplex communication, meaning both client and server can send messages independently. SSE only allows the server to push updates to the client.
import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', ws => { ws.on('message', message => { ws.send(`Server received: ${message}`); }); });
The server listens for messages from a client and sends a response back only to that client with the message prefixed.
Option D correctly imports the WebSocket class from 'ws' and uses the 'on' method with 'message' event and a callback that logs the data.
import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 3000 }); wss.on('connection', ws => { ws.send('Welcome!'); });
The server listens on port 3000 but if clients try to connect to a different port like 8080, connections will fail.
import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', ws => { console.log('Client connected'); ws.on('message', message => { console.log(`Received: ${message}`); wss.clients.forEach(client => { if (client !== ws && client.readyState === 1) { client.send(`Broadcast: ${message}`); } }); }); });
Each client connection triggers 'Client connected' log. When a message is received, 'Received: Hello' is logged. Broadcast messages are sent to clients but not logged on server.
