Performance: ws library for WebSocket server
This affects the server's ability to handle real-time communication efficiently, impacting response time and resource usage.
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); function broadcast(data, sender) { for (const client of wss.clients) { if (client !== sender && client.readyState === WebSocket.OPEN) { client.send(data); } } } wss.on('connection', ws => { ws.on('message', message => { setImmediate(() => broadcast(message, ws)); }); });
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(message); } }); }); });
| Pattern | CPU Usage | Event Loop Blocking | Latency | Verdict |
|---|---|---|---|---|
| Synchronous broadcast on message event | High CPU spikes | Blocks event loop | Increased latency under load | [X] Bad |
| Asynchronous broadcast with setImmediate | Balanced CPU usage | Non-blocking event loop | Lower latency and smoother response | [OK] Good |
ws library in Node.js?wsws library is designed specifically for WebSocket communication, enabling real-time data exchange between server and client.ws.ws library?ws library uses WebSocketServer constructor with an options object, including the port number.new WebSocketServer({ port: 8080 }). Options B, C, and D use incorrect constructors or methods not defined in ws.const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', ws => {
ws.on('message', message => {
console.log(`Received: ${message}`);
ws.send('Hi client');
});
});const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 3000 });
wss.on('connection', function(ws) {
ws.on('message', function(msg) {
ws.send(msg.toUpperCase);
});
});msg.toUpperCase without parentheses, so it passes the function itself instead of calling it.ws.send expects a string or buffer, not a function reference.ws library. Which code snippet correctly sends 'Hello all!' to every client connected to the server?const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
// Broadcast function here
function broadcast(message) {
// ???
}wss.clients set contains all connected clients. We must iterate over it to send messages.readyState === WebSocket.OPEN can receive messages safely.forEach and checks readyState. wss.clients.map(client => client.send(message)); uses map which is not appropriate here. Options A and D use non-existent methods.Pass the test and this pattern moves unknown