Explain WEBSOCKETS  to a kid

Explain WEBSOCKETS to a kid

Imagine you're having a conversation with a friend through text messages on your phone. Normally, when you send a message, your friend receives it and then sends a reply back. This is how regular web communication works too, like when you load a webpage and it sends a request to a server, which then sends back the webpage you requested.

Now, think of web sockets as a way for your phone and your friend's phone to stay connected constantly, like a phone call that never ends. With web sockets, instead of sending a message and waiting for a reply each time, your phone and your friend's phone are always connected, so you can send messages back and forth instantly, without having to wait for a reply every time.

This constant connection allows for real-time communication between your browser (or any other client) and a server. It's like a continuous, two-way street where data can flow freely, making it perfect for things like live chat on websites, online gaming, or any other application where real-time updates are needed.

Why WEBSOCKETS?

  1. Real-time Updates: Web sockets allow for real-time communication between a web browser (or any other client) and a server. This means you can instantly receive updates or messages without needing to refresh the webpage. It's great for applications like live chat, real-time collaboration tools, or online gaming where immediate updates are important.

  2. Reduced Latency: Compared to traditional HTTP requests where the client needs to send a request and wait for a response, web sockets keep a persistent connection open. This reduces the latency (the delay between sending a request and receiving a response), resulting in faster communication between the client and server.

  3. Efficient Communication: Web sockets use a lightweight protocol, which means they have less overhead compared to other methods of real-time communication like long-polling or server-sent events. This makes them more efficient for sending and receiving small amounts of data quickly.

  4. Bi-Directional Communication: Unlike HTTP, which is mainly client-initiated (the client sends a request and the server responds), web sockets allow for bi-directional communication. This means both the client and server can send messages to each other at any time, enabling more interactive and dynamic applications.

  5. Scalability: Web sockets are designed to handle a large number of concurrent connections efficiently. This makes them suitable for building scalable applications that need to support many users simultaneously.

SIMPLE CHAT APPLICATION

//Server.js
const WebSocket = require("ws");
const express = require("express");

const app = express();

const wss = new WebSocket.Server({ port: 3001 });

wss.on('connection', client => {
    client.on('message', message => {
        wss.clients.forEach(ws => {
            if (ws !== client && ws.readyState === WebSocket.OPEN) {
                ws.send(message);
            }
        });
    });
});

const server = app.listen(3002, () => {
    console.log('Server started on port 3002.');
    console.log('WebSocket server running on port 3001.');
});
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            margin: 0;
            padding: 0;
            font-family: 'Poppins', sans-serif;
        }
        .message-row {
            margin-bottom: 10px;
        }
        .bubble {
            padding: 5px 10px;
            border-radius: 10px;
            display: inline-block;
            max-width: 80%;
        }
        .mine {
            background-color: lightblue;
            align-self: flex-end;
            text-align: right;
        }
        .theirs {
            background-color: lightgreen;
        }
    </style>
</head>
<body>
    <div id="messages"></div>
    <form id="messageForm">
        <input type="text" id="messageInput" placeholder="Your message...">
        <button type="submit">Send</button>
    </form>

    <script>
        function showMessage(text, isMine = false){
            document.getElementById("messages").innerHTML += `
                <div class="message-row ${isMine ? 'mine' : 'theirs'}">
                    <div class="bubble">${text}</div>
                </div>
            `;
        }

        const ws = new WebSocket('ws://localhost:3001');
        ws.addEventListener('message', ev => {
            ev.data.text().then(text => {
                showMessage(text, false); // assuming received message is not mine
            });
        });

        document.getElementById("messageForm").addEventListener("submit", function(event) {
            event.preventDefault();
            const messageInput = document.getElementById("messageInput");
            const message = messageInput.value;
            showMessage(message, true); // assuming message sent is mine
            ws.send(message);
            messageInput.value = ""; // clear input field after sending message
        });
    </script>
</body>
</html>

Did you find this article valuable?

Support Thirumalai by becoming a sponsor. Any amount is appreciated!