Source Code:
(back to article)
<?php // Define a function to simulate getting new data function getNewData() { // Simulate getting new data $newData = "New data is available!"; return $newData; } // Set maximum time the server should keep the connection open $maxWaitTime = 30; // seconds $startTime = time(); // Keep the connection open until new data is available or the maximum wait time is reached while (true) { // Check for new data $newData = getNewData(); if ($newData) { // Send new data to the client echo $newData; break; } // Check if the maximum wait time has been reached $waitTime = time() - $startTime; if ($waitTime > $maxWaitTime) { break; } // Sleep for a short period of time before checking for new data again usleep(100000); // 100ms }
Result:
Report an issue