Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@belocer
Created May 21, 2019 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belocer/a6af42136756289aa0758f253a5aaa8f to your computer and use it in GitHub Desktop.
Save belocer/a6af42136756289aa0758f253a5aaa8f to your computer and use it in GitHub Desktop.
EventSource Comet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul id="chat">
</ul>
<script>
let evtSource = new EventSource("index.php");
let chat = document.getElementById('chat');
evtSource.onopen = function(e) {
console.log("Открыто соединение");
};
evtSource.onerror = function(e) {
if (this.readyState == EventSource.CONNECTING) {
console.log("Ошибка соединения, переподключение");
} else {
console.log("Состояние ошибки: " + this.readyState);
}
};
evtSource.onmessage = function(e) {
console.log("Сообщение: " + e.data);
};
evtSource.addEventListener("ping", function(e) {
let newElement = document.createElement("li");
let obj = JSON.parse(e.data);
newElement.innerHTML = "ping at " + obj.time;
chat.appendChild(newElement);
}, false);
</script>
</body>
</html>
<?php
date_default_timezone_set("Russia/Moscow");
header("Content-Type: text/event-stream\n\n");
$counter = rand(1, 10);
while (1) {
# Отправлять событие "ping" каждую секунду
echo "event: ping\n";
$curDate = date(DATE_ISO8601);
echo 'data: {"time": "' . $curDate . '"}';
echo "\n\n";
$counter--;
if (!$counter) {
echo 'data: Время сообщения ' . $curDate . "\n\n";
$counter = rand(1, 10);
}
ob_end_flush();
flush();
sleep(5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment