A PHP script that will handle the persistent http request (backend.php)
A HTML file that will load Javascript code and that will show the data coming from the server (index.html)
The prototype library that will help us to write simple JS code
服务端backend.php:
做2件事:
Write into “data.txt” when new messages are sent
Do an infinite loop as long as “data.txt” file is unchanged
<?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(10000); // sleep 10ms to unload the CPU
clearstatcache();
$currentmodif = filemtime($filename);
}