我想写一个聊天系统。我用过ajax,php和commet porotocol。
一切正常,但是session有一个问题:当session在脚本的顶部启动时,一切都出错(我的脚本无法理解,并且有一个新的msg,所以我必须等待睡眠时间结束)
这是我的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();发布于 2012-07-23 19:58:53
这是因为会话处于锁定状态,避免这种情况的唯一方法是在执行usleep命令之前调用session_write_close()。
基本上,如果一个脚本使用会话,则对于使用相同web浏览器的同一客户端,其他脚本不能同时运行,直到第一个脚本完成或调用session_write_close()。这是因为PHP使用了锁定,看到会话文件被锁定,将等待它再次可用,然后再运行脚本。
https://stackoverflow.com/questions/11611217
复制相似问题