Performance: Setting up WebSocket server
This affects the real-time interaction speed and responsiveness of the web page by enabling persistent, low-latency communication between client and server.
import express from 'express'; import { createServer } from 'http'; import { WebSocketServer } from 'ws'; const app = express(); const server = createServer(app); const wss = new WebSocketServer({ server }); wss.on('connection', ws => { ws.on('message', message => { ws.send(`Echo: ${message}`); }); }); server.listen(3000);
const express = require('express'); const app = express(); const server = app.listen(3000); const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 3000 }); wss.on('connection', ws => { ws.on('message', message => { ws.send(`Echo: ${message}`); }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Separate WebSocket server on same port | 0 (network only) | 0 | 0 | [X] Bad |
| Integrated WebSocket server with Express HTTP server | 0 (network only) | 0 | 0 | [OK] Good |
const WebSocket = require('ws');
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', ws => {
ws.on('message', message => {
console.log(`Received: ${message}`);
});
});
server.listen(3000);const WebSocket = require('ws');
const express = require('express');
const app = express();
const server = http.createServer();
const wss = new WebSocket.Server({ server });
server.listen(3000);wss.on('connection', ws => {
ws.on('message', message => {
// Broadcast message to all clients
???
});
});Pass the test and this pattern moves unknown