業界トップクラスの求人数を誇る転職エージェントPR

リクルートグループのコネクションを活かした非公開求人も充実、他にはない好条件の求人と出会える

1
2

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でtail -Fっぽいやつ

Posted at

ブラウザへのPUSH実装を考え、WebSocketを調べていたら、その何倍も手軽に実装できるServer-Sent EventsというAPIがあるということで、tail -Fっぽく、ファイルが更新されたらブラウザに差分をPUSHするスクリプトを書いてみました。

まず、サーバ側。Mozillaのサンプルを参考に、冒頭でContent-Typeを宣言し、1秒毎にファイルの更新をチェックし、最終更新時間(filemtime)が変わっていれば、差分を
data: ファイルの差分
という形式で出力します。

test.php
<?php

header("Content-Type: text/event-stream\n\n");

$fname = "test.txt";
$ftime = "";
$ftime_old = "";
$contents = "";
$contents_old = "";

while (1) {
    $ftime = filemtime($fname);

    if( $ftime != $ftime_old ){
        $contents = file_get_contents($fname);
        echo 'data:  '.str_replace($contents_old,"",$contents)."\n\n";
        $contents_old = $contents;
    }

    $ftime_old = $ftime;
    clearstatcache();
    ob_end_flush();
    sleep(1);
}

次にブラウザ側。EventSourceオブジェクトを生成し、onmessageハンドラでサーバからPUSHされたデータを読み込み表示します。

index.html
<ul id="eventList"></ul>
<script>
    var eventList = document.getElementById("eventList");
    var evtSource = new EventSource("test.php");

    evtSource.onmessage = function(e) {
        var newElement = document.createElement("li");

        newElement.innerHTML = e.data;
        eventList.appendChild(newElement);
    }
</script>
1
2
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?