24
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Server Sent Events最小限のサンプル(PHP)

Last updated at Posted at 2015-05-22

index.htmlから呼ばれるPHPの実装:

api.php
<?php

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while (1) {
    echo 'data: Hello from server! ' . date('Y-m-d H:i:s'), "\n\n";
    ob_flush();
    flush();
    sleep(1);
}

index.htmlの実装:

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>index.html</title>
</head>
<body>
    <ul id="eventList">
    </ul>
    <script>
        var es = new EventSource('api.php');

        es.addEventListener('message', function (event) {
            console.log(event.data);

            var newElement = document.createElement("li");
            var eventList = document.getElementById('eventList');

            newElement.innerHTML = "message: " + event.data;
            eventList.appendChild(newElement);
        });
    </script>
</body>
</html>
  • Apache
  • PHP(Apacheモジュール)
  • Chrome 43

の環境では特に問題なくできた。

nginx + php-fpmの場合

nginx + php-fpmの場合、普通にしてるとサーバでバッファリングされてしまうので

nginx.confserver {} の中で

fastcgi_keep_conn on; # < solution

proxy_buffering off;
gzip off;

とすればいい。

http://serverfault.com/questions/488767/how-do-i-enable-php-s-flush-with-nginxphp-fpm
によると

header('Content-Encoding: none;');

でもいいと書いてあったが、自分の環境ではうまくいかなかった。

ブラウザ実装状況

http://caniuse.com/#feat=eventsource
Firefox、Chromeはほぼ大丈夫。
Androidは4.4から。
IEは11でもダメ。

24
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?