标签:web php push
这种方式实际上是长连接的最简单实现。和cgi很类似。
PHP实现:
主要是想演示一下几点:
set_time_limit(0);
这个用来保证长连接不会因为php请求超时而中断
ob_flush();
flush(); // used to send the echoed data to the client
这两句共同保证php会即时清空 缓冲并输出
等效于perl中的$|=1
sleep(1);
延时1s.这个太重要了。
用于循环时释放cp
javascript和VB 都没有这个功能。
相关源码:
<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 2008 05:00:00 GMT");
flush();
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Comet php backend</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
set_time_limit(0);
while(1) {
echo '<span>'.time().'<BR></span>';
ob_flush();
flush(); // used to send the echoed data to the client
sleep(1); // a little break to unload the server CPU
}
?>
</body>
</html>