乐闻世界logo
搜索文章和话题

How do I implement basic "Long Polling"?

1个答案

1

What is Long Polling?

Long Polling is a method for implementing server push technology, primarily used when clients need to receive updates in real-time. Traditional polling involves clients periodically sending requests to the server regardless of whether new data is available. In contrast, Long Polling has the client send a request, and the server keeps the connection open until new data is available, at which point it responds and closes the connection. If no data is available, the connection remains open until a predefined timeout, after which the server sends an empty response to the client, who then re-initiates the request upon receiving the response.

How to Implement Long Polling?

Implementing Long Polling primarily involves interaction between the client and server. Here, we use a simple chat application as an example to illustrate how to implement Long Polling.

Server-Side Implementation:

  1. Receive Client Request: Upon receiving a client request, the server first checks for new messages.
  2. Wait for Data: If no new messages are available, the server does not respond immediately but suspends the request.
  3. Respond to Request: When new messages are available, the server immediately returns them as response data to the client.
  4. Timeout Handling: If no new messages are received within a predefined time (e.g., 30 seconds), the server should send an empty response to inform the client that no new data is available.

Implementing with Node.js can be done as follows:

javascript
const express = require('express'); const app = express(); const PORT = 3000; let messageQueue = []; // Simulates a queue for storing messages app.get('/poll', (req, res) => { const sendResponse = (data) => { res.json({ data }); res.end(); }; if (messageQueue.length > 0) { sendResponse(messageQueue.shift()); } else { // If no messages, suspend the request let timeoutId = setTimeout(() => { sendResponse("No new messages"); }, 30000); // 30 seconds later send empty response // If new messages arrive before timeout, cancel timeout and respond req.on('newMessage', () => { clearTimeout(timeoutId); sendResponse(messageQueue.shift()); }); } }); // A simple route to receive and store new messages app.post('/send', (req, res) => { const { message } = req.body; messageQueue.push(message); req.emit('newMessage'); res.status(200).send("Message received"); }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });

Client-Side Implementation:

  1. Send Request: The client sends an HTTP request to the server to initiate polling.
  2. Process Response: Upon receiving the server's response, process the response data (new messages or empty data).
  3. Re-initiate Request: Regardless of whether the response contains new messages or empty data, the client must re-initiate the request to continue polling.

Implementing with JavaScript XMLHttpRequest can be done as follows:

javascript
function poll() { var xhr = new XMLHttpRequest(); xhr.open("GET", "http://localhost:3000/poll", true); xhr.onload = function () { if (xhr.status >= 200 && xhr.status < 300) { // Process data returned from the server console.log('Response:', xhr.responseText); // Continue polling poll(); } }; xhr.onerror = function () { console.error('Request failed'); poll(); }; xhr.send(); } // Start polling poll();

Summary

Long Polling is an effective but potentially resource-intensive method for achieving real-time communication from server to client. While modern web applications tend to prefer more efficient communication methods like WebSocket, Long Polling remains a viable alternative in environments that do not support WebSocket.

2024年8月5日 00:54 回复

你的答案