DEV Community

Simranjit singh
Simranjit singh

Posted on

Understanding Short Polling: A Simple Approach to Client-Server Communication

What is a short polling?

Short polling is a technique used in client-server communication where a client repeatedly sends requests to a server at regular short intervals to check for updates or new data. It's called "short polling" because of the relatively brief delay between each request.

Use case - It is commonly used in scenarios where real-time updates are not critical, such as periodic data updates or system health checks.

How short polling works?

  1. Request Initiation: The client sends a request to the server.
  2. Immediate Response: The server processes the request and responds immediately, even if there is no new data.
  3. Repeat Requests: The client waits for a predetermined interval before sending another request.

Short polling Workings

Advantages

  • Easy to Implement: Simple logic for sending requests.
  • Independent Requests: Each request is independent, which can reduce server memory usage.

Disadvantages

  • Inefficient for Real-Time Needs: High frequency of requests can lead to unnecessary network traffic and server load if updates are infrequent, as the client is constantly polling the server regardless of whether new data is available.
  • Latency: The client may not receive updates immediately, as it relies on the polling interval.
  • Problem with scale: As the number of users grows, the number of network requests will get increased leading to the point number 1.

Below is an example of how you can implement short polling using JavaScript on the client side and Node.js with Express on the server side.

Server-Side (Node.js with Express)

First, set up a simple Express server that responds to client requests.

// server.js
const express = require('express');
const app = express();
const port = 3000;

let data = { message: "Hello, World!" };

app.get('/poll', (req, res) => {
    res.json(data);
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Client-Side (HTML + JavaScript)

Next, create an HTML file with JavaScript to repeatedly send requests to the server at regular intervals.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Short Polling Example</title>
</head>
<body>
    <h1>Short Polling Example</h1>
    <div id="data"></div>

    <script>
        function fetchData() {
            fetch('http://localhost:3000/poll')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('data').innerText = data.message;
                })
                .catch(error => console.error('Error fetching data:', error));
        }

        // Poll the server every 5 seconds
        setInterval(fetchData, 5000);

        // Initial fetch
        fetchData();
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Server-Side:

    • The server listens on port 3000 and responds to GET requests at the /poll endpoint with a JSON object containing a message.
  2. Client-Side:

    • The client uses the fetch API to send a GET request to the server every 5 seconds using setInterval.
    • The response is parsed as JSON and the message is displayed in a div with the ID data.
    • An initial fetch is performed to display data immediately when the page loads.

Running the Example

Start the Server:

  1. Save the server code in a file named server.js.
  2. Run npm init -y to create a package.json file.
  3. Run npm install express to install Express.
  4. Start the server with node server.js.

Open the Client:

  1. Save the client code in an HTML file (e.g., index.html).
  2. Open the HTML file in a web browser.

You should see the message "Hello, World!" displayed on the web page, and it will be updated every 5 seconds as the client polls the server. You can modify the server code to change the data and see how the client updates in real-time.

In summary, while short polling is a useful technique for real-time updates when you don’t need to handle a high volume of users or need immediate real-time data, it is generally less efficient compared to long polling, WebSockets, or Server-Sent Events (SSE), which are more preferred for the scalable solutions.


Top comments (0)