Skip to content

Instantly share code, notes, and snippets.

@lukemorton
Forked from rwaldron/event-source.html
Created June 1, 2011 16:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lukemorton/1002722 to your computer and use it in GitHub Desktop.
Save lukemorton/1002722 to your computer and use it in GitHub Desktop.
EventSource: The Glorified Long Polling Machine
Open your console.
<script src="event-source.js"></script>
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);
<?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();
}
@lukemorton
Copy link
Author

The reason for output_buffering = off, is because by default it is set to 4096 which means PHP will wait until 4096 bytes of information are stored in the buffer before it flushes, even if in your script you try to do it before this limit is reached. Alternately you could just get this script to output 4096+ bytes and you wouldn't have to change a thing in your php.ini.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment