Complete the code to create a WebSocket server using the 'ws' library.
import WebSocket from 'ws'; const wss = new WebSocket.Server({ [1]: 8080 });
The 'port' option specifies the port number the WebSocket server listens on.
Complete the code to send a message to all connected WebSocket clients.
wss.clients.forEach(client => {
if (client.readyState === [1]) {
client.send('Hello clients!');
}
});Only clients with the 'OPEN' readyState can receive messages.
Fix the error in the WebSocket client connection code.
const ws = new WebSocket('ws://localhost:[1]');
The server listens on port 8080, so the client must connect to that port.
Fill both blanks to broadcast a JSON message to all clients except the sender.
wss.on('connection', ws => { ws.on('message', message => { wss.clients.forEach(client => { if (client !== ws && client.readyState === [1]) { client.send(JSON.[2](message)); } }); }); });
Clients must be open to receive messages, and messages must be stringified JSON to send.
Fill all three blanks to set up a WebSocket server that logs connection and message events.
import WebSocket from 'ws'; const server = new WebSocket.Server({ [1]: 9090 }); server.on('[2]', ws => { console.log('Client connected'); ws.on('[3]', message => { console.log('Received:', message); }); });
The server listens on port 9090, listens for 'connection' events, and listens for 'message' events on each client.