-
-
Save pwFoo/5dd7e7ed6cfeeb9d57a45356ec26321d to your computer and use it in GitHub Desktop.
EventSource: The Glorified Long Polling Machine
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
Open your console. | |
<script src="event-source.js"></script> |
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
document.addEventListener("DOMContentLoaded", function() { | |
/* | |
EventSource is nothing more then a glorified | |
long polling machine. It will create HTTP requests | |
to a provided url of the same origin | |
(which in turn creates an `open` event ) until | |
it sees a valid "text/event-stream" response body | |
at which point a `message` event will be fired. | |
This process will repeat until the EventSource is | |
terminated my calling its close() method. | |
no "data: " message from the server should result in long polling | |
`open` events being fired, followed by zero `message` events | |
*/ | |
var // declare localized references | |
eventSrc = new EventSource( "event-source.php" ), | |
handler = function( event ) { | |
console.log( [ event.type, new Date(), event, event.data ] ); | |
}, | |
getReadyState = function( src ) { | |
if ( src.readyState ) { | |
// readyState is almost always 0, we're only interested in | |
// seeing readyState OPEN (1) ( or CLOSED (2) ) | |
console.log( [ src.readyState, new Date() ] ); | |
} | |
setTimeout(function() { | |
getReadyState( src ); | |
}, 1); | |
}; | |
console.log( eventSrc ); | |
// Setup event handlers | |
[ "open", "message" ].forEach( function( name ) { | |
eventSrc.addEventListener( name, handler, false ); | |
}); | |
// Begin sampling the ready state | |
getReadyState( eventSrc ); | |
}, false); |
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
<?php | |
// Make sure we are starting an event stream | |
header("Content-Type: text/event-stream\n\n"); | |
// Continue in an infinite loop | |
while (true) | |
{ | |
// Every second we will push "hello world" | |
sleep(1); | |
echo "data: hello world \n\n"; | |
// This will ensure our data is sent provided you set this | |
// in your php.ini: | |
// output_buffering = off | |
ob_flush(); | |
flush(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://kevinchoppin.dev/blog/server-sent-events-in-php