Rumah >pembangunan bahagian belakang >tutorial php >nginx下要使用Server-Sent Events要如何配置?

nginx下要使用Server-Sent Events要如何配置?

WBOY
WBOYasal
2016-06-06 20:40:112105semak imbas

使用php+js实现服务器推,在wamp环境中可以生效,但转移到Linux下的nginx上,就不能用了,是环境配置问题?要如何配置?
以下是相关代码
服务器端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);
}
</code>

前端js:

<code>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);
</code>

回复内容:

使用php+js实现服务器推,在wamp环境中可以生效,但转移到Linux下的nginx上,就不能用了,是环境配置问题?要如何配置?
以下是相关代码
服务器端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);
}
</code>

前端js:

<code>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);
</code>

因为nginx缓冲区问题,默认nginx是有缓冲区,php的刷新输出对nginx无效的。
需要输出前面再加个

<code>header('X-Accel-Buffering: no');</code>
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:codeigniter总是提示404Artikel seterusnya:php与node.js的性能差距