0

我想写一个聊天系统。我使用过 ajax、php 和 commet porotocol。

一切正常,但会话有问题:当会话在脚本顶部启动时,一切都出错了(我的脚本无法理解有一个新的消息,所以我必须等待睡眠时间结束)

这是我的 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);
}

// return a json array
$response = array();
$response['msg']       = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
4

1 回答 1

1

那是因为会话被锁定,避免这种情况的唯一方法是session_write_close()在你的 usleep 命令之前调用。

基本上,如果一个脚本使用会话,则在第一个脚本完成或调用session_write_close(). 这是因为 PHP 使用锁定,并且看到会话文件被锁定,并在运行脚本之前等待它再次可用。

于 2012-07-23T11:58:52.863 回答