Complete the code to create a WebSocket server that listens on port 8080.
import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: [1] });
The WebSocket server listens on port 8080, which is a common port for WebSocket connections during development.
Complete the code to send a message to a connected client when the connection opens.
wss.on('connection', function connection(ws) { ws.[1]('Hello Client!'); });
The send method is used to send data to the connected client over the WebSocket.
Fix the error in the code to properly handle incoming messages from clients.
wss.on('connection', function connection(ws) { ws.on('[1]', function message(data) { console.log('Received:', data); }); });
The message event is emitted when the server receives data from a client.
Fill both blanks to broadcast a message to all connected clients.
wss.clients.forEach(function each(client) {
if (client.readyState === [1]) {
client.[2]('Broadcast message');
}
});Clients with readyState === 1 are open and ready to receive messages. Use send to send the message.
Fill all three blanks to close a client connection with a status code and reason.
ws.[1]([2], '[3]');
The close method closes the connection. Code 1000 means normal closure, and the string explains the reason.