Leave a Comment
Server sent events (sse) с примерами использования
https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events
http://www.html5rocks.com/en/tutorials/eventsource/basics/
Всё сводится к:
на сервере (php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
date_default_timezone_set("America/New_York"); header("Content-Type: text/event-stream\n\n"); $counter = rand(1, 10); while (1) { // Every second, sent 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_flush(); flush(); sleep(1); } |
на клиенте
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var evtSource = new EventSource("ssedemo.php"); evtSource.onmessage = function(e) { var newElement = document.createElement("li"); newElement.innerHTML = "message: " + e.data; eventList.appendChild(newElement); } evtSource.addEventListener("ping", function(e) { var newElement = document.createElement("li"); var obj = JSON.parse(e.data); newElement.innerHTML = "ping at " + obj.time; eventList.appendChild(newElement); }, false); |
Similar Posts
LEAVE A COMMENT
Для отправки комментария вам необходимо авторизоваться.