PHP
Server-Sent-Events

Server Sent Events の使い方

次のページを参考にしました。
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

実行結果
sse_mar2101.png

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Server Sent Event</title>
<link href="event01.css" rel="stylesheet">
<script src="event01.js"></script>
</head>
<body onload="initial();">
<header>
<h1>event01</h1>
</header>
<article>
        <ol id="msgs"></ol>
</article>
<hr />
Mar/21/2018 PM 12:16<p />
</body>
</html>
event01.css
h1 { font-size: 14pt; padding: 1px 10px;
        border-style: solid; border-width: 0px 0px 2px 7px; border-color:green; }

body { background: #EEFFEE; }

article { background: white; margin: 10px 0px;  padding: 10px; }
event01.js
// -------------------------------------------------------------------
/*
    event01.js

                    Mar/21/2018
*/
// -------------------------------------------------------------------
var EventSource = window.EventSource || window.MozEventSource

function initial ()
{
        if (!EventSource){
            alert("EventSourceが利用できません。")
            return
        }

var source = new EventSource ('event01.php')

source.onmessage = function(event)
    {
    var ol = document.getElementById('msgs')
    ol.innerHTML = '<li>' + event.data + '</li>' + ol.innerHTML
    }
}

// -------------------------------------------------------------------
event01.php
<?php
// ------------------------------------------------------------------
//  event01.php
//
//                  Mar/21/2018
//
// ------------------------------------------------------------------
date_default_timezone_set('Asia/Tokyo');

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

$counter = rand(1, 10);
while (1) {
  // Every second, send a "ping" event.

  echo "event: ping\n";
  $curDate = date(DATE_ISO8601);
  echo 'data: {"time": "' . $curDate . '"}';
  echo "\n\n";

  // Send a simple message at random intervals.

  $counter--;

  if (!$counter) {
    echo 'data: This is a message at time ' . $curDate . "\n\n";
    $counter = rand(1, 10);
  }

  ob_end_flush();
  flush();
  sleep(1);
}

// ------------------------------------------------------------------
?>