php - server sent events while loop takes so much time for page load, when page is refreshed or F5 is pressed -
i using server sent events query database new records , display events user
here code
javascript
window.onload = function setdatasource() { if (!!window.eventsource) { var source = new eventsource("polling.php"); source.addeventlistener("message", function(e) { console.log(e.data); }, false); source.addeventlistener("open", function(e) { console.log("opened"); }, false); source.addeventlistener("error", function(e) { console.log(e); if (e.readystate == eventsource.closed) { console.log("closed"); } }, false); } else {}}
php
<?php header("content-type: text/event-stream\n\n"); include_once dirname(__file__) . '/db.php'; session_start(); while (1) { $response = getnewmessages(); echo 'data: message '. json_encode1($response)."\n\n"; ob_flush(); flush(); sleep(5); } function getnewmessages () { // query database , new records. }
it works fine , gets new records every 5 seconds. problem here when refresh page manually,it takes time page load.
when page loading, can figure out while loop still executes (at least thrice) , pauses page. after time page starts loading normally. doubt while loop pausing execution
can please suggest me how overcome situation ? or how can replace while loop?
two problems: 1. php file-based sessions lock session file while it's in use 2. php cannot detect client has disconnected until after tries output
so, worst case, refresh script runs, dumps out updates, , sleeps 5 seconds. if client refreshes @ exact same moment, take 5 loop iteration occur, , output produced, allowing php realize connection's closed.
quick fix: session_write_close()
release lock on session file, allowing parallel requests occur.
long term fix: use better polling loop check messages, e.g. websockets.
Comments
Post a Comment