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:
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:
sleep();
what will happen to other simultaneous requests?Kindly guide me with this problem... Thanks
Yes, that's an idea. You should keep in mind though that this script will not end, and an instance of PHP will be spawned for every user. I'm using the longpoll logic with v8cgi server side. After the client started an XMLHttp Request (XHR), the server starts checking with intervals for new input. I have added a timer server side, to send a response every 5 minutes, after which the client - if not disconnected - resends the XHR and the procedure repeats.
So every instance of the server side mechanism runs no longer than 5 minutes max because if the client is disconnected, the response the server sends after 5 minutes isn't followed by a new XHR.
The process looks like this: