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

WBOY
풀어 주다: 2016-06-06 20:40:11
원래의
2033명이 탐색했습니다.

使用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>
로그인 후 복사
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!