Created
January 21, 2019 16:15
-
-
Save g105b/8bce1da26279bb9c7f07ca61bfeda50f to your computer and use it in GitHub Desktop.
SSE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
header("Access-Control-Allow-Origin: *"); | |
$accept = $_SERVER["HTTP_ACCEPT"]; | |
if($accept === "text/event-stream") { | |
header("Content-Type: text/event-stream"); | |
header('Cache-Control: no-cache'); | |
$i = 0; | |
while($i < 10) { | |
$time = time(); | |
echo "id: $time\n"; | |
echo "event: gregupdate\n"; | |
echo "data: {message: \"test\"}\n"; | |
echo "\n"; | |
flush(); | |
ob_flush(); | |
sleep(1); | |
$i++; | |
} | |
exit; | |
} | |
if(!empty($_POST)) { | |
$msg = $_POST["message"] ?? null; | |
if($msg) { | |
file_put_contents("messages.txt", $msg . PHP_EOL, FILE_APPEND); | |
header("Location: /"); | |
exit; | |
} | |
} | |
$msgList = []; | |
if(is_file("messages.txt")) { | |
$msgList = file("messages.txt"); | |
} | |
?> | |
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<title>SSE test</title> | |
</head> | |
<body> | |
<div id="output" style="white-space: pre"> | |
<?php | |
foreach($msgList as $msg) { | |
echo $msg . PHP_EOL; | |
} | |
?> | |
</div> | |
<form method="post"> | |
<input name="message" placeholder="Message" /> | |
<button>Submit</button> | |
</form> | |
<script> | |
let source = new EventSource(location.href); | |
source.onmessage = function(event) { | |
console.log(event); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment