0
0
Node.jsframework~10 mins

Server-Sent Events alternative in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a WebSocket server using the 'ws' library.

Node.js
import WebSocket from 'ws';
const wss = new WebSocket.Server({ [1]: 8080 });
Drag options to blanks, or click blank then click option'
Aserver
Bhost
Cpath
Dport
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'host' instead of 'port' will not start the server on the correct port.
2fill in blank
medium

Complete the code to send a message to all connected WebSocket clients.

Node.js
wss.clients.forEach(client => {
  if (client.readyState === [1]) {
    client.send('Hello clients!');
  }
});
Drag options to blanks, or click blank then click option'
AWebSocket.OPEN
BWebSocket.CONNECTING
CWebSocket.CLOSED
DWebSocket.CLOSING
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'CLOSED' or 'CLOSING' will cause errors because the connection is not open.
3fill in blank
hard

Fix the error in the WebSocket client connection code.

Node.js
const ws = new WebSocket('ws://localhost:[1]');
Drag options to blanks, or click blank then click option'
A8080
B3000
C80
D443
Attempts:
3 left
💡 Hint
Common Mistakes
Using port 80 or 443 will fail if the server is not listening there.
4fill in blank
hard

Fill both blanks to broadcast a JSON message to all clients except the sender.

Node.js
wss.on('connection', ws => {
  ws.on('message', message => {
    wss.clients.forEach(client => {
      if (client !== ws && client.readyState === [1]) {
        client.send(JSON.[2](message));
      }
    });
  });
});
Drag options to blanks, or click blank then click option'
AWebSocket.OPEN
Bparse
Cstringify
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using JSON.parse to send messages will cause errors.
5fill in blank
hard

Fill all three blanks to set up a WebSocket server that logs connection and message events.

Node.js
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);
  });
});
Drag options to blanks, or click blank then click option'
Aport
Bconnection
Cmessage
Dopen
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'open' instead of 'connection' will not work for server events.