WebSocket is a modern communication protocol that enables full-duplex, bidirectional communication between a client (usually a web browser) and a server over a single, persistent TCP connection. Unlike traditional HTTP communication, which follows a request-response model, WebSocket allows both the client and the server to send data at any time without repeatedly establishing new connections.
WebSocket is widely used in applications that require real-time data updates such as chat applications, online gaming, stock trading platforms, collaborative tools, and live notifications. It significantly improves performance and reduces latency compared to traditional polling or long-polling techniques.
Before WebSocket, developers relied on techniques like HTTP polling, long polling, and server-sent events to achieve real-time communication. These methods had limitations such as high latency, increased bandwidth consumption, and inefficient server usage.
WebSocket solves these problems by providing:
WebSocket begins with an HTTP request called a handshake. The client sends an HTTP request to the server with an "Upgrade" header, requesting to switch the protocol from HTTP to WebSocket.
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Version: 13
If the server supports WebSocket, it responds with a status code 101 (Switching Protocols).
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Once the handshake is complete, the connection remains open, allowing both client and server to exchange messages in real time.
Both client and server can send messages simultaneously, enabling true real-time interaction.
The connection remains open until explicitly closed, eliminating the need for repeated HTTP requests.
Since there is no need to establish a new connection for each message, data transfer is faster.
WebSocket uses minimal headers compared to HTTP, reducing bandwidth usage.
Servers handle fewer connections compared to traditional polling methods.
| Feature | WebSocket | HTTP |
|---|---|---|
| Communication Type | Bidirectional | Unidirectional |
| Connection | Persistent | Short-lived |
| Latency | Low | Higher |
| Overhead | Low | High |
| Use Case | Real-time apps | Static content |
Modern browsers provide a built-in WebSocket API that allows developers to easily create and manage WebSocket connections.
const socket = new WebSocket("ws://localhost:3000");
socket.onopen = function() {
console.log("Connection established");
};
socket.onmessage = function(event) {
console.log("Message received: " + event.data);
};
socket.onclose = function() {
console.log("Connection closed");
};
socket.onerror = function(error) {
console.log("Error: ", error);
};
socket.send("Hello Server!");
Below is an example of a simple WebSocket server using Node.js and the ws library.
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 3000 });
server.on('connection', (socket) => {
console.log("Client connected");
socket.on('message', (message) => {
console.log("Received:", message);
socket.send("Server received: " + message);
});
socket.on('close', () => {
console.log("Client disconnected");
});
});
WebSocket messages are sent in frames. Each frame contains:
Real-time messaging between users.
Live updates and multiplayer interactions.
Instant price updates and alerts.
Push notifications for updates.
Real-time document editing and collaboration.
Always use wss:// instead of ws:// to encrypt data using TLS.
Implement token-based authentication for secure communication.
Validate incoming data to prevent attacks.
Prevent abuse by limiting the number of requests.
Long polling repeatedly sends HTTP requests to the server, whereas WebSocket maintains a persistent connection.
Use WebSocket when:
Avoid WebSocket when:
WebSocket is a powerful protocol that enables real-time, bidirectional communication between clients and servers. It has revolutionized the way modern web applications handle live data, making applications faster, more interactive, and efficient. By understanding how WebSocket works and implementing best practices, developers can build highly responsive applications that meet modern user expectations.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved