First I would like to appreciate all of you great people for being so helpful to new programmers.
I have a question about long polling. I have studied some articles about Long polling technique of Comet Programming. The method seems a lot difficult to me because it also sometimes requires installing some scripts on the server side.
Now I have found an example on long polling. Its working great but I am not sure if it is the proper method. The example script is about a chat-like application. This php script works as follows:
- The php script checks the data.txt file continuously until it is changed.
- As soon as the data.txt is changed, the new text is outputted on the webpage.
Here is the php script:
<?php
$filename = dirname(__FILE__).'/data.txt';
// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
file_put_contents($filename,$msg);
die();
}
// infinite loop until the data file is not modified
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
usleep(500000); // sleep 500ms to unload the CPU
clearstatcache();
$currentmodif = filemtime($filename);
}
// return a json array
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
?>
I am not including the webpage code to keep the question simple. The webpage has just a div which shows the text of data.txt whenever it is changed.
Main points of my question are:
- Is this looping method the proper method to long poll the server?
- Also when the server is executing
sleep();what will happen to other simultaneous requests? - Is there any technique to reduce the load on server due to long polling's continuous script?
- If a client starting this long poll request disconnects, how can we know and stop the script for that disconnected client accordingly?
Kindly guide me with this problem... Thanks