Using php + js to implement server pushing can take effect in the wamp environment, but it cannot be used if it is transferred to nginx in Linux. Is it an environment configuration problem? How do I configure it? The following code is the php code on the server: {code ...} front-end js: {code ...} using php + js to implement server pushing can take effect in the wamp environment, but it cannot be used if it is transferred to nginx in Linux. Is it an environment configuration problem? How do I configure it?
The following code is used:
Php code on the server:
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); $('p#header p#user_notice a').text(obj.time); }, false);
Reply content:
Using php + js to implement server pushing can take effect in the wamp environment, but it cannot be used if it is transferred to nginx in Linux. Is it an environment configuration problem? How do I configure it?
The following code is used:
Php code on the server:
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); $('p#header p#user_notice a').text(obj.time); }, false);
Due to nginx buffer problems, nginx has a buffer by default, and the php refresh output is invalid for nginx.
Add one before output
header('X-Accel-Buffering: no');