HTTP vs WebSocket communication protocols

Dec 16, 2024

HTTP and WebSocket are both communication protocols that allow clients and servers to communicate, but they differ in how they handle communication:

HTTP vs WebSocket

HTTP

A request-response protocol that requires a new connection for each data exchange. HTTP is a one-way connection that's been the basis of websites since their debut.

HTTP

A TCP three-way handshake is used to establish a connection between the client and server. The client sends a request to the server, and the server responds with a response. This exchange of messages is repeated for each request-response cycle. https://www.coursera.org/articles/three-way-handshake

WebSocket

A full-duplex protocol that maintains a continuous connection, allowing real-time, two-way communication between the client and server. WebSockets are well suited for real-time applications like chat, notifications, and voice or video calls.

WebSocket

For example: Binance, Backpack, A real-time chat app, and many more.

A simple HTTP server in express:

// Create an express server
const express = require('express');
const app = express();

// Define a simple route
app.get('/', (req, res) => {
    res.send('Hello, World!');
});

// Start the server
const PORT = 3000; // Choose your port
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Creating a WebSocket server in Node.js:

const WebSocket = require('ws');

// Create a WebSocket server
const wss = new WebSocket.Server({ port: 8080 });

console.log('WebSocket server is running on ws://localhost:8080');

// Handle connection event
wss.on('connection', (ws) => {
    console.log('New client connected!');

    // Send a message to the client
    ws.send('Welcome to the WebSocket server!');

    // Handle incoming messages from the client
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
        // Echo the received message back to the client
        ws.send(`You sent: ${message}`);
    });

    // Handle client disconnection
    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

more to be added soon...

Mounish Vatti