0
0
Node.jsframework~10 mins

WebSocket protocol concept 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 that listens on port 8080.

Node.js
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: [1] });
Drag options to blanks, or click blank then click option'
A3000
B443
C8080
D80
Attempts:
3 left
💡 Hint
Common Mistakes
Using port 80 or 443 without proper permissions or HTTPS setup.
Choosing a random port number not commonly used for WebSocket.
2fill in blank
medium

Complete the code to send a message to a connected client when the connection opens.

Node.js
wss.on('connection', function connection(ws) {
  ws.[1]('Hello Client!');
});
Drag options to blanks, or click blank then click option'
Asend
Breceive
Copen
Dconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'receive' which is not a method on the WebSocket object.
Confusing event names with methods.
3fill in blank
hard

Fix the error in the code to properly handle incoming messages from clients.

Node.js
wss.on('connection', function connection(ws) {
  ws.on('[1]', function message(data) {
    console.log('Received:', data);
  });
});
Drag options to blanks, or click blank then click option'
Amessage
Bconnect
Csend
Dopen
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'open' or 'connect' which are not message events.
Confusing method names with event names.
4fill in blank
hard

Fill both blanks to broadcast a message to all connected clients.

Node.js
wss.clients.forEach(function each(client) {
  if (client.readyState === [1]) {
    client.[2]('Broadcast message');
  }
});
Drag options to blanks, or click blank then click option'
A1
B0
Csend
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using readyState 0 which means connecting, not open.
Using 'close' instead of 'send' to send messages.
5fill in blank
hard

Fill all three blanks to close a client connection with a status code and reason.

Node.js
ws.[1]([2], '[3]');
Drag options to blanks, or click blank then click option'
Aclose
B1000
CNormal closure
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' instead of 'close' to close the connection.
Using an incorrect status code or missing the reason string.