Understanding Long Polling in Node.js
Alexandre Pereira
Software Engineer MERN | React.JS | Nodejs | Javascript | Typescript | MongoDB | GCP | Python
Long polling is a technique used in web applications to create real-time interactions between the client and the server. It allows the server to send updates to the client without the client constantly checking for new information. This technique is especially useful when working with environments that do not support WebSockets.
In this article, I’ll explain how long polling works and provide a simple example using Node.js.
How Does Long Polling Work?
Long polling works as follows:
Example of Long Polling in Node.js
Here is a basic implementation of long polling in Node.js:
Server-side (Node.js)
领英推荐
const express = require('express');
const app = express();
const PORT = 3000;
let messages = []; // Stores messages for clients to retrieve
// Endpoint for clients to send messages
app.post('/send', express.json(), (req, res) => {
const { message } = req.body;
if (message) {
messages.push(message);
res.status(200).send('Message received!');
} else {
res.status(400).send('Message is required!');
}
});
// Endpoint for long polling
app.get('/poll', (req, res) => {
if (messages.length > 0) {
// If there are messages, send them to the client
res.json({ messages });
messages = []; // Clear the messages after sending
} else {
// Hold the connection for 30 seconds
const timeout = setTimeout(() => {
res.json({ messages: [] }); // Send an empty response after timeout
}, 30000);
// If new messages arrive, clear the timeout and send the messages
messages.push = function (message) {
Array.prototype.push.call(this, message);
clearTimeout(timeout);
res.json({ messages: this });
messages = [];
};
}
});
app.listen(PORT, () => {
console.log(`Server is running on https://localhost:${PORT}`);
});
Client-side (JavaScript)
async function pollServer() {
try {
const response = await fetch('https://localhost:3000/poll');
const data = await response.json();
if (data.messages && data.messages.length > 0) {
console.log('New messages:', data.messages);
}
// Immediately poll again
pollServer();
} catch (error) {
console.error('Polling error:', error);
setTimeout(pollServer, 5000); // Retry after 5 seconds if an error occurs
}
}
// Start polling
pollServer();
When to Use Long Polling
Long polling is a good solution when:
However, long polling can increase server load because of the repeated HTTP connections, so consider WebSockets or Server-Sent Events (SSE) for more efficient real-time communication when possible.
Conclusion
Long polling is a reliable technique for achieving real-time updates in applications, especially when WebSockets are not an option. With the example above, you can implement basic long polling in your Node.js projects.
Let me know if you have used long polling or other real-time techniques in your projects! ??
Senior .NET Software Engineer | Senior Full Stack Developer | C# | .Net Framework | Azure | React | SQL | Microservices
3 个月Interesting! Thanks for sharing with us!
.NET Developer | C# | TDD | Angular | Azure | SQL
3 个月Thanks for sharing! Long polling enables real-time updates in Node.js by holding client-server connections, offering a solid fallback when WebSockets aren’t an option.
Very informative, Thank you!!!
Software Engineer | Software Developer | Backend Developer | C# | .NET Core | AWS Certified | Angular
3 个月Very informative