Created
April 2, 2020 22:57
-
-
Save progerio/52c985e677e577fc389d52d36bcfb713 to your computer and use it in GitHub Desktop.
Example sse component
This file contains hidden or 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
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Server-sent events demo</title> | |
</head> | |
<body> | |
<button>Close the connection</button> | |
<ul> | |
</ul> | |
<script> | |
var button = document.querySelector('button'); | |
var evtSource = new EventSource('ola.php'); | |
console.log(evtSource.withCredentials); | |
console.log(evtSource.readyState); | |
console.log(evtSource.url); | |
var eventList = document.querySelector('ul'); | |
evtSource.onopen = function () { | |
console.log("Connection to server opened."); | |
}; | |
evtSource.onmessage = function (e) { | |
var newElement = document.createElement("li"); | |
newElement.textContent = "message " +" ||| "+ e.lastEventId + " --- " + e.data; | |
eventList.prepend(newElement); | |
console.log("M" + e.data); | |
}; | |
evtSource.addEventListener('ping', function (e) { | |
var newElement = document.createElement("li"); | |
newElement.textContent = "ping " +" ||| " + e.lastEventId + " --- " + e.data; | |
eventList.prepend(newElement); | |
console.log("P" + e.data); | |
}); | |
evtSource.addEventListener('close', function (e) { | |
var newElement = document.createElement("li"); | |
newElement.textContent = "FIM " +" ||| " + e.lastEventId + " --- " + e.data; | |
eventList.prepend(newElement); | |
console.log("FFFFFFF" + e.data); | |
}); | |
evtSource.onerror = function () { | |
console.log("EventSource failed."); | |
}; | |
button.onclick = function () { | |
console.log('Connection closed'); | |
evtSource.close(); | |
}; | |
// 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); | |
</script> | |
</body> | |
</html> | |
//Backend | |
<?php | |
$d = new \HomeBaked\Http\HttpServerSentListener(); | |
$d->addServerEvent('message', function() { | |
$f = ''; | |
return [ | |
'nome' => 'Texto:: '.$f, | |
'idade' => '123' | |
]; | |
}); | |
$d->addServerEvent('ping', function() { | |
return 'Hora-Time: ' . time(); | |
}); | |
$d->onClose(function(){ | |
return 'foi....'; | |
}); | |
$d->setTime(2)->dispatch(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment