37,721
社区成员
发帖
与我相关
我的任务
分享
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
import web
from email.Utils import formatdate
urls = (
'/','index'
)
class index:
def GET(self):
return "data: The server time is:"+formatdate(localtime=True)
if __name__ == "__main__":
app = web.application(urls,globals())
app.run()
import web
import datetime
urls = (
'/','index'
)
class index:
def GET(self):
return "data: The server time is:"+str(datetime.datetime.now())
if __name__ == "__main__":
app = web.application(urls,globals())
app.run()
<!DOCTYPE html>
<html>
<body>
<h1>获得服务器更新</h1>
<div id="result"></div>
<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("/update");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br />";
};
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
服务端代码:
class Update:
def GET(self):
web.header('Content-type','text/event-stream')
web.header('Cache-Control','no-cache')
return 'data:'+datetime.datetime.now().strftime('%Y%m%d%H%M%S')
输出结果:
获得服务器更新
20130726161615
20130726161620
20130726161625
20130726161630
20130726161635
20130726161640
20130726161645
20130726161650
20130726161655
20130726161700
20130726161705
20130726161710
20130726161715
20130726161720
20130726161725
20130726161730
20130726161735
20130726161740
20130726161745
20130726161750
20130726161755
20130726161800
20130726161805
20130726161810class index:
def GET(self):
web.header('Content-Type','text/event-stream')
web.header('Cache-Control', 'no-cache')
return "data: The server time is:"+formatdate(localtime=True)
不过始终记得那句话“所有主流浏览器均支持服务器发送事件,除了 Internet Explorer。”