Blog about Web Programming and Electronics
💬 👤
back Back to blog
WEB (HTML, CSS, PHP)

What is WebSocket and How It Enables Real-Time Communication

The classic HTTP protocol relies on a request-response model: the client (browser) must always initiate a request to receive data from the server. However, for applications requiring real-time data display—such as live chats, instant notifications, financial charts, or live sensor monitoring—this approach is too slow. This is where WebSocket comes in, establishing a real-time, two-way persistent connection.

Difference Between HTTP and WebSocket Protocols

The main difference between the two protocols lies in how the connection is maintained and the direction of data flow.

Feature HTTP Protocol WebSocket Protocol
Connection Short-lived (opens and closes per request) Persistent (remains open after initial handshake)
Communication Direction One-way (only the client initiates requests) Full-Duplex (both endpoints send data anytime)
Latency Higher (due to repeated HTTP headers) Extremely low (data travels instantly)

How the Handshake Works

The process of establishing a WebSocket connection begins with a standard HTTP request containing a special protocol upgrade request (Upgrade Header).

  1. HTTP Upgrade Request: The client sends a request to the server asking to switch to the `ws://` or `wss://` protocol.
  2. Handshake Response: If the server supports WebSocket, it responds with HTTP status 101 Switching Protocols.
  3. Two-Way Channel: The connection remains open. The server can now push data to the client at any time without a prior request.

Example of Using WebSocket in JavaScript

In the browser, using WebSockets is very straightforward thanks to the built-in WebSocket object.

// Establishing a connection with the WebSocket server
const socket = new WebSocket('wss://example.com/socket');

// Event handler for successful connection
socket.onopen = function(event) {
  console.log('WebSocket connection established!');
  socket.send(JSON.stringify({ type: 'init', clientId: 42 }));
};

// Receiving real-time data from the server
socket.onmessage = function(event) {
  const data = JSON.parse(event.data);
  console.log('New message from server:', data);
  
  // Updating an element on the page immediately upon data receipt
  document.getElementById('live-status').innerText = data.status;
};

// Event handler for connection closure
socket.onclose = function(event) {
  console.log('Connection closed.');
};

Using WebSocket in Arduino and ESP32 Projects

WebSocket is also extremely popular on ESP32 microcontrollers. When the ESP32 operates as a WebSocket server, you can stream sensor readings (such as live temperature or energy consumption) directly to a web dashboard multiple times per second without reloading the page or overloading the network.

back Back to blog