PHPSSE:Server-sentEvents,一个简单有效的库,通过PHP实现了HTML5的服务器发送事件,用于实时从服务器推送事件到客户端,比Websocket更容易。
要求:PHP5.4orlater
示例代码JavascriptdemoClient:receivingeventsfromtheserver
//withCredentials=true: pass the cross-domain cookies to server-sidevar source = new EventSource("https://127.0.0.1:9001/push.php", {withCredentials:true});source.addEventListener("new-msgs", function(event){ console.log(event.data);//get data}, false);PHPdemoServer:sendingeventsfromtheserverbypurephp
include './vendor/autoload.php';use Hhxsv5\SSE\SSE;use Hhxsv5\SSE\Update;header('Content-Type: text/event-stream');header('Cache-Control: no-cache');header('Connection: keep-alive');header('X-Accel-Buffering: no');//Nginx: unbuffered responses suitable for Comet and HTTP streaming applications(new SSE())->start(new Update(function () { $id = mt_rand(1, 1000); $newMsgs = [ [ 'id' => $id, 'title' => 'title' . $id, 'content' => 'content' . $id, ], ];//get data from database or servcie. if (!empty($newMsgs)) { return json_encode(['newMsgs' => $newMsgs]); } return false;//return false if no new messages}), 'new-msgs');
评论