Understanding Long Polling in Node.js

Understanding Long Polling in Node.js

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:

  1. The client sends a request to the server.
  2. The server does not respond immediately. It holds the connection open until there is new data or the request times out.
  3. When the server has new data, it sends a response to the client.
  4. The client processes the response and immediately sends a new request, repeating the process.

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:

  • Real-time updates are needed.
  • WebSockets are not supported in your environment.
  • The server does not have frequent updates.

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! ??

Mauro Marins

Senior .NET Software Engineer | Senior Full Stack Developer | C# | .Net Framework | Azure | React | SQL | Microservices

3 个月

Interesting! Thanks for sharing with us!

回复
Lucas Wolff

.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!!!

回复
Arilson Silva

Software Engineer | Software Developer | Backend Developer | C# | .NET Core | AWS Certified | Angular

3 个月

Very informative

要查看或添加评论,请登录

Alexandre Pereira的更多文章

社区洞察

其他会员也浏览了