0
0
Expressframework~10 mins

Setting up WebSocket server in Express - Interactive Practice

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

Complete the code to import the WebSocket library.

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

Complete the code to create a WebSocket server on top of an existing HTTP server.

Express
const wss = new WebSocket.Server({ [1] });
Drag options to blanks, or click blank then click option'
Ahost: 'localhost'
Bserver: httpServer
Cport: 8080
Dpath: '/ws'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing 'port' instead of 'server' when attaching to an HTTP server.
Using 'host' or 'path' options incorrectly here.
3fill in blank
hard

Fix the error in the WebSocket connection event handler to correctly receive the client socket.

Express
wss.on('connection', function([1]) {
  console.log('Client connected');
});
Drag options to blanks, or click blank then click option'
Aclient
BwsServer
Csocket
Dconnection
Attempts:
3 left
💡 Hint
Common Mistakes
Using the server object as the parameter instead of the client socket.
Naming the parameter 'connection' which is the event name, not the argument.
4fill in blank
hard

Fill both blanks to send a message to the client when a connection is established.

Express
wss.on('connection', function(socket) {
  socket.[1]('[2]');
});
Drag options to blanks, or click blank then click option'
Asend
Bemit
Cmessage
DHello, client!
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'emit' which is from other libraries like socket.io.
Passing an event name instead of a message string.
5fill in blank
hard

Fill all three blanks to handle incoming messages and log them.

Express
wss.on('connection', function(socket) {
  socket.on('[1]', function([2]) {
    console.log('Received:', [3]);
  });
});
Drag options to blanks, or click blank then click option'
Amessage
Bdata
Dconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'connect' event instead of 'message'.
Using wrong parameter names or forgetting to log the data.