首先是首页,包含一个文本输入和一个显示聊天内容的iframe,还有一个隐藏iframe用来提交form表单:
<BR><?php <BR>//chat.php <BR>header('cache-control: private'); <BR>header('Content-Type: text/html; charset=utf-8'); <BR>?> <BR> <BR><script type="text/javascript"> <BR>function submitChat(obj) { <BR>obj.submit(); <BR>document.getElementsByName('content')[0].value = ''; <BR>} <BR></script> <BR><iframe src="./chat_content.php" height="300" width="100%"></iframe> <BR><iframe name="say" height="0" width="0"></iframe> <BR> <BR> <BR> <BR> <BR>
另外一个就是保存用户提交的聊天内容了,我简单的写一下文本,而且没有做什么锁定,这个只是简易版本:
<BR><?php <BR>$content = trim($_POST['content']); <BR>if ($content) { <BR>$fp = fopen('./chat.txt', 'a'); <BR>fwrite($fp, $content . "\n"); <BR>fclose($fp); <BR>clearstatcache(); <BR>} <BR>?> <BR>
接下来看主要的HTTP长连接部分,也就是chat_content.php文件:
<BR><?php <BR>header('cache-control: private'); <BR>header('Content-Type: text/html; charset=utf-8'); <BR>//测试设置30秒超时,一般会设置比较长时间。 <BR>set_time_limit(30); <BR>//这一行是为了搞定IE这个BT <BR>echo str_repeat(' ', 256); <BR>ob_flush(); <BR>flush(); <BR>$fp = new SplFileObject('./chat.txt', 'r+'); <BR>$line = 0; <BR>$totalLine = 0; <BR>while (!$fp->eof()) { <BR>$fp->current(); <BR>$totalLine++; <BR>$fp->next(); <BR>} <BR>$fp->seek($totalLine); <BR>$i = $totalLine - 1; <BR>while (true) { <BR>if (!$fp->eof()) { <BR>if ($content = trim($fp->current())) { <BR>echo '<div>'; <BR>echo htmlspecialchars($content); <BR>echo "
“;
flush();
$fp->next();
$i++;
}
} else {
$fp->seek($i – 1);
$fp->next();
}
{
//这里可以添加心跳检测后退出循环
}
usleep(1000);
}
?>