Long polling is a technique used in web development to allow a client to receive an immediate response from a server, or to wait for a certain event to occur before receiving a response. It is often used in scenarios where real-time communication is required, such as chat applications or live updates.
Basic Concept
In a long polling scenario, the client sends a request to the server and the server holds the request open until a certain event occurs. Once the event occurs, the server sends a response back to the client, and the client then sends another request to the server, and so on.
Steps:
- The client sends a request to the server.
- The server holds the request open until a certain event occurs.
- The server sends a response back to the client.
- The client sends another request to the server.
Example
Here is a simple example of how long polling can be implemented using JavaScript and PHP:
// Client-side JavaScript
function longPolling() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/en/developer_docs/long_polling_example', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
longPolling();
}
};
xhr.send();
}
longPolling();
// Server-side PHP
<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Simulate a delay
sleep(5);
// Simulate an event
$event = "New message received";
// Send the response back to the client
echo $event;
}
?>
Conclusion
Long polling is a powerful technique for implementing real-time communication between a client and a server. It is simple to implement and can be used in a variety of scenarios. For more information on long polling, you can refer to the MDN Web Docs.