0
0
Node.jsframework~5 mins

ws library for WebSocket server in Node.js - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the ws library in Node.js?
The ws library is used to create WebSocket servers and clients in Node.js, enabling real-time, two-way communication between a server and browser or other clients.
Click to reveal answer
beginner
How do you create a basic WebSocket server using the ws library?
You create a WebSocket server by importing <code>WebSocketServer</code> from <code>ws</code> and then instantiating it with a port number, like:<br><pre>const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });</pre>
Click to reveal answer
beginner
What event do you listen to for new client connections on a ws WebSocket server?
You listen to the 'connection' event on the WebSocket server instance to handle new client connections.
Click to reveal answer
beginner
How can you send a message to a connected client using the ws library?
You use the send() method on the client WebSocket object inside the 'connection' event handler, like ws.send('Hello client!').
Click to reveal answer
beginner
Why is it important to handle the 'message' event on a WebSocket client connection?
Handling the 'message' event lets the server receive and process data sent from the client, enabling interactive real-time communication.
Click to reveal answer
Which method creates a WebSocket server with the ws library?
Aws.createServer(8080)
Bnew WebSocketServer({ port: 8080 })
Cnew WebSocketClient({ port: 8080 })
Dws.startServer(8080)
What event should you listen to for new client connections?
A'connection'
B'client'
C'open'
D'connect'
How do you send a message to a client in ws?
Aclient.send(message)
Bclient.emit('send', message)
Cserver.send(client, message)
Dws.sendToClient(message)
Which of these is NOT a valid use of the ws library?
ACreating a WebSocket server
BCreating a WebSocket client
CHandling HTTP requests
DSending real-time messages
What event do you listen to for receiving messages from a client?
A'input'
B'data'
C'receive'
D'message'
Explain how to set up a simple WebSocket server using the ws library in Node.js.
Think about the steps from starting the server to talking with clients.
You got /4 concepts.
    Describe the role of the 'connection' and 'message' events in a ws WebSocket server.
    Focus on how the server interacts with clients.
    You got /4 concepts.