myHotTake

Tag: long polling

  • Long Polling vs WebSockets: Which is Best for Real-Time Apps?

    If you find this story useful, feel free to like or share it!


    I’m at a beach, and I’m trying to stay connected with my friend who’s somewhere in the ocean. Long polling is like me standing at the shore, constantly sending messages in bottles into the sea, asking, “Hey, any news?” I throw a bottle, wait for a reply, and if I don’t get one soon enough, I send another. Sometimes, my friend sends back a bottle saying, “Nothing new yet,” and I just keep repeating this process. It’s a bit tiring and not very efficient, but it works—I eventually get the message when something important happens.

    Now, let’s switch to a more advanced method. WebSockets is like me having a walkie-talkie tuned into my friend’s frequency. Once we’ve established this connection, it’s like an open line, allowing us to chat in real-time. If my friend spots a dolphin or something exciting, they can instantly buzz me, “Hey, check this out!” without me having to keep sending bottles. It’s a smooth, continuous conversation, and I can respond just as quickly. This keeps our communication fluid and immediate, letting us share the beach experience without the delays and effort of sending constant messages.

    Through this story, I see long polling as the message-in-a-bottle method, where communication is possible but a bit slow and cumbersome. In contrast, WebSockets transform our interaction into a seamless, real-time exchange, making the beach adventure much more dynamic and lively.


    Long Polling

    Long polling is like our message-in-a-bottle system. Here’s a basic example using JavaScript with a server-side setup like Node.js and Express:

    // Client-side JavaScript (browser)
    function longPoll() {
        fetch('/poll')
            .then(response => response.json())
            .then(data => {
                console.log('Message from server:', data.message);
                // Immediately start another poll after receiving a response
                longPoll();
            })
            .catch(error => console.error('Polling error:', error));
    }
    
    // Start long polling
    longPoll();
    // Server-side JavaScript (Node.js with Express)
    const express = require('express');
    const app = express();
    
    app.get('/poll', (req, res) => {
        // Simulate server delay and send a message back
        setTimeout(() => {
            res.json({ message: 'Here is a new update!' });
        }, 5000); // 5 seconds delay
    });
    
    app.listen(3000, () => console.log('Server running on port 3000'));

    Here, the client keeps sending requests to the server, waiting for new updates. Once an update is received, it immediately sends another request, just like throwing another bottle into the sea.

    WebSockets

    With WebSockets, we establish a continuous connection, like using a walkie-talkie. Here’s how it looks:

    // Client-side JavaScript (browser)
    const socket = new WebSocket('ws://localhost:3000');
    
    socket.onopen = () => {
        console.log('Connected to server');
    };
    
    socket.onmessage = event => {
        console.log('Message from server:', event.data);
    };
    
    socket.onerror = error => {
        console.error('WebSocket error:', error);
    };
    // Server-side JavaScript (Node.js with WebSocket library)
    const WebSocket = require('ws');
    const server = new WebSocket.Server({ port: 3000 });
    
    server.on('connection', socket => {
        console.log('Client connected');
        socket.send('Welcome to WebSocket server!');
    
        // Simulate sending messages every 5 seconds
        setInterval(() => {
            socket.send('Here is a new update!');
        }, 5000);
    });

    With WebSockets, once the connection is established, the server can push updates to the client whenever they occur, allowing real-time communication without the need for repeated requests.

    Key Takeaways

    1. Long Polling is a more traditional method where the client repeatedly requests updates from the server. It can be less efficient due to constant request-response cycles but is easier to implement on servers that don’t support WebSockets.
    2. WebSockets provide a persistent, full-duplex communication channel, enabling instant data exchange between client and server. This approach is ideal for applications requiring real-time updates, such as chat apps and live notifications.
    3. Choosing between these technologies depends on the specific requirements of your application, including the server’s capabilities and the expected traffic.