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?
- Request Initiation: The client sends a request to the server.
- Immediate Response: The server processes the request and responds immediately, even if there is no new data.
- Repeat Requests: The client waits for a predetermined interval before sending another request.
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}`);
});
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>
Explanation
-
Server-Side:
- The server listens on port 3000 and responds to GET requests at the
/poll
endpoint with a JSON object containing a message.
- The server listens on port 3000 and responds to GET requests at the
-
Client-Side:
- The client uses the
fetch
API to send a GET request to the server every 5 seconds usingsetInterval
. - The response is parsed as JSON and the message is displayed in a
div
with the IDdata
. - An initial fetch is performed to display data immediately when the page loads.
- The client uses the
Running the Example
Start the Server:
- Save the server code in a file named
server.js
. - Run
npm init -y
to create apackage.json
file. - Run
npm install express
to install Express. - Start the server with
node server.js
.
Open the Client:
- Save the client code in an HTML file (e.g.,
index.html
). - 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)