Using PHP+JS to implement server Push, in the WAMP environment can be effective, but transferred to the Nginx under Linux, it is not used, is the environment configuration problem? How do I configure it?
The following is the relevant code
Server-side PHP code:
date_default_timezone_set("America/New_York");header("Content-Type:text/event-stream");$userid = $_SESSION['userid'];//session_write_close();$db = get_db();while(true) { $notices = $db->lRange("User:{$userid}:Notice", 0, -1); $notice_num = 0; foreach ($notices as $value) { $readed = $db->hGet("Notice:{$value}:Info", 'readed'); if ($readed == false) { $notice_num++; } } echo "event: ping\n"; $curDate = $notice_num; echo 'data: {"time": "' . $curDate . '"}'; echo "\n\n"; ob_flush(); flush(); sleep(30);}
Front-end JS:
var evtSource = new EventSource(serverName + 'index.php/Home/NoticePush/index'); evtSource.addEventListener("ping", function(e) { var obj = JSON.parse(e.data); $('div#header div#user_notice a').text(obj.time); }, false);
Reply content:
Using PHP+JS to implement server Push, in the WAMP environment can be effective, but transferred to the Nginx under Linux, it is not used, is the environment configuration problem? How do I configure it?
The following is the relevant code
Server-side PHP code:
date_default_timezone_set("America/New_York");header("Content-Type:text/event-stream");$userid = $_SESSION['userid'];//session_write_close();$db = get_db();while(true) { $notices = $db->lRange("User:{$userid}:Notice", 0, -1); $notice_num = 0; foreach ($notices as $value) { $readed = $db->hGet("Notice:{$value}:Info", 'readed'); if ($readed == false) { $notice_num++; } } echo "event: ping\n"; $curDate = $notice_num; echo 'data: {"time": "' . $curDate . '"}'; echo "\n\n"; ob_flush(); flush(); sleep(30);}
Front-end JS:
var evtSource = new EventSource(serverName + 'index.php/Home/NoticePush/index'); evtSource.addEventListener("ping", function(e) { var obj = JSON.parse(e.data); $('div#header div#user_notice a').text(obj.time); }, false);
Because the nginx buffer problem, the default nginx is a buffer, PHP refresh output to nginx invalid.
Need to output the front and add a
header('X-Accel-Buffering: no');