合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
[TOC] ## 示例 ### php 实现 <details> <summary>index.html</summary> ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="example"></div> <script> var source = new EventSource('http://127.0.0.1:7000/test.php'); var div = document.getElementById('example'); source.onopen = function (event) { div.innerHTML += '<p>Connection open ...</p>'; }; source.onerror = function (event) { div.innerHTML += '<p>Connection close.</p>'; }; source.addEventListener('connecttime', function (event) { div.innerHTML += ('<p>Start time: ' + event.data + '</p>'); }, false); source.onmessage = function (event) { div.innerHTML += ('<p>Ping: ' + event.data + '</p>'); }; </script> </body> </html> ``` </details> <br /> <details> <summary>index.php</summary> ``` <?php header("HTTP/1.1 200 OK"); header("Content-Type:text/event-stream"); header("Content-Control:no-cache"); header("Connection:keep-alive"); header("Access-Control-Allow-Origin:*"); echo "retry: 100\n"; echo "event: connecttime\n"; echo "data: ".time()."\n\n"; echo "data: session_id ".session_id()."\n\n"; flush(); ob_flush(); while(true){ echo "data: ".time()."\n"; echo "data: ".time()."\n\n"; flush(); ob_flush(); usleep(500000); } ``` </details> <br /> 执行 ``` > php -S 0.0.0.:7000 ``` 注意: 使用 php -S 会阻塞, 使用Apache 等方式,只是在EventSource的url 会卡,其他不会