DEV Community

Cover image for WebSockets 101: Simple Explanation and First Project in 5 Minutes
Vin Cooper
Vin Cooper

Posted on

WebSockets 101: Simple Explanation and First Project in 5 Minutes

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'));
Enter fullscreen mode Exit fullscreen mode

});
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)