0
0
Node.jsframework~10 mins

ws library for WebSocket server 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 import the ws library.

Node.js
const WebSocket = require('[1]');
Drag options to blanks, or click blank then click option'
Aws
Bexpress
Chttp
Dsocket.io
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'express' or 'http' instead of 'ws'.
Using 'socket.io' which is a different library.
2fill in blank
medium

Complete the code to create a new WebSocket server on port 8080.

Node.js
const wss = new WebSocket.Server({ [1]: 8080 });
Drag options to blanks, or click blank then click option'
Aurl
Bhost
Caddress
Dport
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'host' or 'address' instead of 'port'.
Using 'url' which is not a valid option here.
3fill in blank
hard

Fix the error in the event listener to correctly handle new connections.

Node.js
wss.on('[1]', function connection(ws) {
  ws.send('Welcome!');
});
Drag options to blanks, or click blank then click option'
Amessage
Bconnection
Copen
Dconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'connect' or 'open' which are not valid events for the server.
Confusing 'message' event with connection event.
4fill in blank
hard

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

Node.js
wss.clients.forEach(function [1](client) {
  if (client.readyState === [2].OPEN) {
    client.send('Hello all!');
  }
});
Drag options to blanks, or click blank then click option'
AforEach
BWebSocket
Cws
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'ws' instead of 'WebSocket' for the readyState constant.
Using 'send' as the function name instead of 'forEach'.
5fill in blank
hard

Fill all three blanks to handle incoming messages and reply back.

Node.js
wss.on('connection', function(ws) {
  ws.on('[1]', function(message) {
    console.log('Received:', message.toString());
    ws.[2]('Echo: ' + [3]);
  });
});
Drag options to blanks, or click blank then click option'
Amessage
Bsend
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' event instead of 'message'.
Trying to send the wrong variable or forgetting to convert message to string.