Many modern applications work in real time: messengers, cryptocurrency exchanges, online games, and collaborative services. How do they instantly transmit data without page refreshes? The answer is WebSockets.
WebSockets allow for a persistent connection between the client and the server, enabling instant data exchange. In this article, weβll break down how they work and create a simple WebSocket server and client in just 5 minutes! π
π₯ How Do WebSockets Work?
Traditional HTTP requests operate on a request-response model:
The client sends a request.
The server processes and sends back a response.
The connection is closed.
WebSockets work differently:
The client and server establish a connection using the ws:// or wss:// (secure WebSocket) protocol.
The connection remains open, allowing the server to send data at any time.
The client and server can send messages asynchronously with no delay.
π Where Are WebSockets Used?
β
Online chats (e.g., WhatsApp Web, Slack)β
Cryptocurrency exchanges (real-time prices on Binance, WhiteBIT)β
Online games (fast transmission of game events)β
Collaborative editing (Google Docs, Figma)β
Trading platforms and financial dashboards
π First WebSockets Project in 5 Minutes
Letβs create a WebSocket server and client using Node.js. Youβll need:
Node.js (install from the official website)
The ws library for WebSockets
π 1. Setting Up a WebSocket Server
Create a project folder and install the necessary package:
mkdir websocket-demo && cd websocket-demo
npm init -y
npm install ws
Create a file server.js and add the following code:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
console.log('Client connected');
socket.on('message', (message) => {
console.log('Received message:', message);
socket.send(`Echo: ${message}`);
});
socket.on('close', () => console.log('Client disconnected'));
});
console.log('WebSocket server running at ws://localhost:8080');
Start the server:
node server.js
π 2. Connecting a WebSocket Client
Open the browser console and enter:
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
console.log('Connected to server');
socket.send('Hello, server!');
};
socket.onmessage = (event) => {
console.log('Message from server:', event.data);
};
socket.onclose = () => console.log('Connection closed');
Congratulations! π Now the server and client can communicate in real time.
Top comments (0)