php
1●サーバー側(sse.php) 2<?php 3header('Content-Type: text/event-stream'); 4header('Cache-Control: no-cache'); 5 6$count=5; 7$roop_kaisuu=3; 8if($count >= $roop_kaisuu){ 9 $max_count=$count - $roop_kaisuu; 10}else{ 11 $max_count=0; 12} 13 14$id = array(51, 52, 53, 54, 55); 15$chat = array('チャット51', 'チャット52', 'チャット53', 'チャット54', 'チャット55最新'); 16 17while(true){ 18 //3行表示------------------------------------------ 19 for($i= $count-1 ; $i >= $max_count; $i--) { 20 print "data:<{$id[$i]}>{$chat[$i]}\n\n"; 21 } 22 23 ob_flush(); 24 flush(); 25 26 sleep(3); 27 //3行表示------------------------------------------ 28} 29?>
html
1●クライアント側(index.html) 2<!DOCTYPE html> 3<html lang="ja"> 4<head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>SSE</title> 8</head> 9<body> 10 <h1>SSE</h1> 11 <div id="result"></div> 12 13 <script> 14 if (!!window.EventSource) { 15 var source = new EventSource('sse.php'); 16 17 source.onmessage = function(event) { 18 var resultDiv = document.getElementById('result'); 19 resultDiv.innerHTML += event.data + '<br>'; 20 }; 21 22 source.onerror = function(event) { 23 console.error("EventSource failed:", event); 24 }; 25 } else { 26 console.log("Your browser doesn't support SSE."); 27 } 28 </script> 29</body> 30</html>
