Consider this Express server setup with WebSocket. What message does the server send to the client upon connection?
import express from 'express'; import { WebSocketServer } from 'ws'; const app = express(); const server = app.listen(3000); const wss = new WebSocketServer({ server }); wss.on('connection', ws => { ws.send('Welcome client!'); });
Look at the ws.send inside the connection event handler.
The server listens for new WebSocket connections. When a client connects, the connection event fires and the server sends the message 'Welcome client!' immediately.
Choose the correct way to create a WebSocket server that shares the same HTTP server as Express.
The WebSocket server needs the actual HTTP server instance, not the Express app.
The WebSocketServer constructor requires the HTTP server object. Calling app.listen(3000) returns the HTTP server, which is passed as server option.
Identify the cause of the error in this code snippet:
import express from 'express'; import { WebSocketServer } from 'ws'; const app = express(); const wss = new WebSocketServer({ server: app }); wss.on('connection', ws => { ws.send('Hello'); }); app.listen(3000);
Check what server option expects in WebSocketServer constructor.
The WebSocketServer expects an HTTP server instance, but app is an Express application, not the server. This causes a runtime error.
Consider this code that counts connected clients:
import express from 'express'; import { WebSocketServer } from 'ws'; const app = express(); const server = app.listen(3000); const wss = new WebSocketServer({ server }); let count = 0; wss.on('connection', ws => { count++; ws.on('close', () => { count--; }); });
Each new connection increments count by 1.
When 3 clients connect, the connection event fires 3 times, incrementing count to 3. No clients disconnected yet.
Why must the WebSocket server share the HTTP server instance created by Express?
Think about how WebSocket connections start as HTTP requests.
WebSocket connections begin as HTTP requests that are upgraded to WebSocket protocol. Sharing the HTTP server allows handling both HTTP and WebSocket on the same port seamlessly.