Web Sockets vs HTTP

Kaushal Dhakal
5 min readJul 20, 2023

--

WebSockets and HTTP are both communication protocols used in web applications, but they serve different purposes and have distinct characteristics.

Here’s a comparison of WebSockets vs. HTTP:

  1. Communication Type:

HTTP: HTTP (Hypertext Transfer Protocol) is a request-response protocol. Clients (usually web browsers) send HTTP requests to the server, and the server responds with the requested data. It is a stateless protocol, meaning each request is independent of previous requests, and no persistent connection is maintained.

WebSockets: WebSockets, on the other hand, provide full-duplex communication, enabling real-time, bidirectional communication between the client and server. It establishes a persistent connection that remains open, allowing data to be sent and received in both directions without the need to initiate a new connection for each exchange.

2. Connection Overhead:

HTTP: Each HTTP request-response cycle introduces connection overhead, as a new connection is established and closed for each request-response transaction. This overhead can impact real-time applications that require frequent data updates.

WebSockets: WebSockets reduce connection overhead significantly since the connection is established once, and subsequent data can be sent and received over the same connection. This makes WebSockets more suitable for real-time applications with low latency requirements.

3. Use Cases:

HTTP: HTTP is widely used for traditional web applications and RESTful APIs. It is well-suited for scenarios where clients request resources from the server and receive responses.

WebSockets: WebSockets are ideal for applications that demand real-time, interactive communication, such as chat applications, real-time gaming, stock market tickers, collaborative tools, and other applications that require frequent data updates and low-latency interactions.

4. Server Load:

HTTP: The stateless nature of HTTP and the need to establish new connections for each request can lead to higher server load and overhead, especially in scenarios with many clients making frequent requests.

WebSockets: WebSockets help reduce server load by maintaining a persistent connection and enabling efficient bidirectional communication, which is particularly advantageous in situations where constant communication is needed.

5. Browser Support:

HTTP: All modern web browsers support HTTP, and it is the fundamental protocol used to access web pages and resources.

WebSockets: Most modern web browsers support WebSockets, making them widely available for web developers to use in their applications.

In summary, HTTP is well-suited for traditional web applications that involve one-off requests and responses, while WebSockets are designed for real-time applications that require low latency and continuous bidirectional communication. Depending on the specific requirements of your application, you may choose to use HTTP, WebSockets, or a combination of both to provide the best user experience.

Polling:

Polling is related to HTTP, but it is not a specific feature of the HTTP protocol itself. Instead, polling is a technique used in web applications to simulate real-time updates when WebSockets are not available or practical.

In traditional HTTP request-response communication, the client (e.g., a web browser) sends a request to the server, and the server responds with the requested data. After receiving the response, the client may need to wait for a specific interval or user action before sending another request to get updated data from the server. This process is known as “polling.”

There are two common types of polling:

  1. Regular Polling (Standard Polling):
  • In regular polling, the client sends periodic HTTP requests to the server at fixed intervals, asking for updates or new data.
  • The server responds to each request with the latest information, even if there are no updates.
  • If there are no updates, the client still needs to handle the unnecessary responses, which can lead to extra network traffic and potential server load.

2. Long Polling:

  • Long polling is an improvement over regular polling that helps reduce unnecessary traffic and provides near real-time updates.
  • In long polling, the client sends an HTTP request to the server, and the server holds the request open until new data is available or a certain timeout is reached.
  • When new data is available, the server responds to the client, and the client immediately processes the response and sends another request to initiate the next long poll.
  • If no new data is available before the timeout, the server responds with an empty response, and the client immediately sends another request to initiate the next long poll.
  • This way, the client can receive updates as soon as they are available, minimizing the delay between updates and providing a pseudo-real-time experience.

While polling can provide a way to achieve real-time updates in web applications, it has some drawbacks compared to WebSockets. Polling generates more network traffic due to frequent requests and responses, and it may not be as efficient as WebSockets for real-time communication. WebSockets, being a full-duplex communication protocol, offer a more efficient and responsive solution for real-time applications, making them the preferred choice when real-time updates are crucial.

Client Side:

<!DOCTYPE html>
<html>

<head>
<title>WebSocket Client</title>
</head>

<body>
<div>
<label for="message">Enter a message:</label>
<input type="text" id="message" />
<button onclick="sendMessage()">Send</button>
</div>
<div id="output"></div>

<script>
const webSocket = new WebSocket("ws://localhost:8080");

//Connection
webSocket.onopen = () => {
console.log("Connected to server");
}
webSocket.onerror = (err) => {
console.log("Error on Connection.", err);
}

function sendMessage() {
var inputText = document.getElementById("message");

var data = JSON.stringify({
id: `User-${Math.floor(Math.random() * 10)}`,
content: inputText.value
});
webSocket.send(data);
inputText.value = "";
}
webSocket.onclose = () => {
console.log("Server disconnected.");
}

webSocket.onmessage = (event) => {
const outputDiv = document.getElementById('output');
console.log("Message from server", event.data);
const reader = new FileReader();
reader.onload = function (event) {
const content = event.target.result;
outputDiv.innerHTML += `<p>${content}</p>`;
}
reader.readAsText(event.data);
}
</script>
</body>

</html>

Server Side:

const { json } = require("stream/consumers");
const { WebSocketServer } = require("ws");

// Create a WebSocket server
const socketServer = new WebSocketServer({
port: 8080,
});

socketServer.on("connection", (socket) => {
console.log("Someone connected........");
socket.on("error", (err) => {
console.log("error occured......", err);
});
socket.on("message", (data) => {
//Sending message to everyone excluding the client that initiated requested.
socketServer.clients.forEach((client) => {
if (client !== socket) {
client.send(data);
}
});
});
socket.on("close", () => {
console.log("Client Disconnected..");
});
});

console.log("WebSocket server is listening on port 8080");

In the provided code, a WebSocket server is implemented using the ws library in Node.js, and a WebSocket client is implemented using JavaScript in the browser. The server accepts incoming WebSocket connections and broadcasts received messages to all connected clients except the one that initiated the message.

Summary of the server code:

  1. The server creates a WebSocket server listening on port 8080.
  2. When a client connects (connection event), the server logs a message to the console.
  3. The server handles incoming messages from clients (message event) and broadcasts the received message to all connected clients (excluding the sender).
  4. When a client disconnects (close event), the server logs a message to the console.

Summary of the client code:

  1. The client creates a WebSocket connection to ws://localhost:8080.
  2. The client provides event handlers for the connection (onopen), error (onerror), close (onclose), and received messages (onmessage).
  3. When the user enters a message and clicks the “Send” button, the client sends a JSON object as a string to the server using webSocket.send(data).
  4. The client receives messages from the server (onmessage event) and displays the received content on the web page.

The server and client code work together to enable real-time communication between clients and the server through WebSockets. Clients can send messages to the server, and the server broadcasts those messages to all other connected clients, creating a simple chat-like application. The server and client communicate using JSON objects, and the received data is displayed on the web page.

Note that this is a simplified example, and in a real-world application, you would need to handle more complex scenarios, error handling, security considerations, and scalability. Additionally, it’s essential to properly sanitize and validate the user input to avoid security vulnerabilities in a production environment.

--

--

Kaushal Dhakal
Kaushal Dhakal

Written by Kaushal Dhakal

Software Engineer . I write blog posts about web development, JavaScript, Java ,React, Node and Problem Solving.

No responses yet