Created
May 21, 2019 05:42
-
-
Save belocer/a6af42136756289aa0758f253a5aaa8f to your computer and use it in GitHub Desktop.
EventSource Comet
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
<!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> |
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 | |
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