Introduction to WebSocket in JavaScript: What is Real-Time Communication?
In the modern web, users are accustomed to instant updates: messages in chats arrive without page reloads, stock quotes change in real time, and in online games, opponents' actions are visible immediately. All of this became possible thanks to the WebSocket technology — a protocol that provides a persistent bidirectional connection between the client and the server.
Unlike a classic HTTP request, where the client sends a request and waits for a response, WebSocket allows the server to send data to the client at any time. This opens up endless possibilities for creating real-time applications in JavaScript. In this article, we will cover WebSocket from the basics to building a full-fledged chat on Node.js.
WebSocket Basics: How the Protocol Works
What is WebSocket and How is it Different from HTTP?
WebSocket is a communication protocol that works over TCP. It starts as an HTTP request (handshake), after which the connection is "upgraded" to WebSocket, and data is transmitted in both directions without additional headers. This makes it ideal for applications where low latency is important.
Main advantages of WebSocket over traditional methods (Polling, Long Polling):
- Persistent connection — no need to create a new HTTP request for each update
- Low latency — data is transmitted instantly as soon as it appears on the server
- Traffic savings — minimal frame size (only 2 bytes of overhead data)
- Bidirectional communication — the server can initiate data sending
Establishing a Connection: The Handshake
The process starts with an HTTP request from the client containing the header Upgrade: websocket. The server, supporting WebSocket, responds with status 101 Switching Protocols. After this, the connection is considered established.
// Example HTTP request for WebSocket setupGET /chat HTTP/1.1Host: example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13Creating a WebSocket Server on Node.js
Installing and Configuring the ws Library
To work with WebSocket on the server side, we will use the popular ws library. It is lightweight, fast, and fully compliant with the protocol specification.
// Installing the library// npm install wsLet's create a simple WebSocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => { console.log('New client connected'); ws.on('message', (message) => { console.log('Received message:', message.toString()); // Send a response to all connected clients wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(`Echo: ${message}`); } }); }); ws.send('Welcome to the WebSocket server!');});
console.log('WebSocket server started on port 8080');Connecting a Client in JavaScript
On the client side (browser), the built-in WebSocket object is used:
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => { console.log('Connection established'); socket.send('Hello, server!');};
socket.onmessage = (event) => { console.log('Message from server:', event.data);};
socket.onclose = () => { console.log('Connection closed');};
socket.onerror = (error) => { console.error('WebSocket error:', error);};