This is the right method for Long Polling (comet programming)

First, I would like to appreciate all of you, great people, for being so useful to new programmers.

I have a question about a lengthy survey. I studied some articles about the long comet polling method . The method seems very difficult to me because sometimes it is necessary to install some scripts on the server side.

Now I found an example with a lengthy survey. It works great, but I'm not sure if this is the correct method. The sample script refers to a chat-like application. This PHP script works as follows:

  • The php script constantly checks the data.txt file until it is modified.
  • As soon as the data.txt file changes, new text is displayed on the web page.

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();
?>

-, . - div, data.txt , .

:

  • looping ?
  • , sleep();, ?
  • - script?
  • , , , script ?

...

+5
2

, . , script , PHP . longpoll v8cgi. , XMLHttp (XHR), . , 5 , - - XHR, .

, 5 , , , , 5 , XHR.

:

  • XHR
  • - :
    • XHR
    • .
  • 5 :
    • () XHR
  • - :
  • [...]
  • 5 :
  • [...]
  • (= XHR )
+5

, , , . , .

, , , . , , , http .

api , node.js

+1

All Articles