Loading lesson path
WebSockets provide a persistent connection between client and server, allowing for real-time, bidirectional communication.
Formula
This is different from traditional HTTP, which follows a request - response model.: Instantly push data to clients
: No need for repeated HTTP requests
: Both client and server can send messages
: Messages are sent immediately
Formula
Understanding the difference between WebSockets and HTTP is crucial for building real - time applications effectively.Persistent, single connection
Formula
Bidirectional, full - duplex
Unidirectional, request - responseTraditional web pages, APIs
Chat apps, live feeds Loading web pages, form submissions
WebSockets begin with an HTTP handshake (status code 101) before upgrading to the WebSocket protocol (ws:// or wss://).
Formula
mkdir websocket - demo cd websocket - demo npm init - y
Then, install the ws package:npm install ws
The ws module is a simple, fast, and thoroughly tested WebSocket client and server implementation.
Let's create a simple WebSocket server that echoes back any message it receives. Create a new file called server.js
Example: WebSocket Echo Server const WebSocket = require('ws');
Formula
// Create a WebSocket server on port 8080 const wss = new WebSocket.Server({ port: 8080 });console.log('WebSocket server is running on ws://localhost:8080');
// Connection event handler wss.on('connection', (ws) => {
console.log('New client connected');
// Send a welcome message to the client ws.send('Welcome to the WebSocket server!');
// Message event handler ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Echo the message back to the client ws.send(`Server received: ${message}`);
});
// Close event handler ws.on('close', () => {
console.log('Client disconnected');
});
});