DataMoney.net

Web-server_sent_event_web数据推送技术

andy发表:2020-04-22 03:13:14

#>0.  
  我所知道的有4种,1.服务器steam方式直接服务器死循环 (注意用ob_flush做每次输出的清旧与更新).2.ajax发起请求,服务器配合以死循环输出.3.websocket这是全双工模式一般都有三方库或框架集成,重型武器大型项目.4.html5的新功能EventSource,本文重点介绍下.单向单工只做推送用的利器.建议直接看
    w3schools  官方文档

#>1.这个功能是H5新推出,浏览器们支持率如何?
    大部分都支持,微软你就别多想,最稳就是他----不会支持的.
    以下js代码去判断你的浏览器api是否有此方法
    typeof(EventSource)    //正常输出是 "function",不支持此方法就是"undefined"

#>2.代码参考
    
// web 前端代码 if (typeof(EventSource) == 'function' ){ var source = new EventSource("http://datamoney.com/push.php"); source.onopen = function(event) { console.log('contect success!'); } source.onmessage = function(event) { console.log("收到推送的消息了:"+event.data); }; source.onerror = function(event) { console.log('wrong!'); } }else{ //$.ajax老套路此处略过 } //服务器代码push.php // 将“ Content-Type”标头设置为“ text / event-stream” header('Content-Type: text/event-stream'); // 指定页面不应该缓存 header('Cache-Control: no-cache'); $result ='{"code":200,"pushtime":"'+time()+'","apiname":"push"}'; // 注意!!!发送的数据(始终以“ data:”开头)因为前端要用event.data读数据. echo "data: {$result}"; 将输出数据刷新回网页 flush();