Chrome 6: Server Push Events with new EventSource()
Posted by Rick Waldron
This is mighty awesome. I’ve put together some test demos, to run them you’ll first need to get this Chromium build:
Then download these:
https://gist.github.com/415116
client.html
<script src="event-source.js"></script>;
event-source.js
document.addEventListener('DOMContentLoaded', function () {
var eventSrc = new EventSource('events.php');
eventSrc.addEventListener('open', function (event) {
console.log(event.type);
});
eventSrc.addEventListener('message', function (event) {
console.log(event.type);
console.log(event.data);
});
}, false);
events.php
<?php
header("Content-Type: text/event-stream\n\n");
// despite not having the while(true){}
// this seems to repeat pushing messages to the client
echo 'data: ' . time() . "\n";
?>
For something (only slightly) more involved
https://gist.github.com/415294
event-source-2.html
<script src="event-source-2.js"></script>
event-source-2.js
document.addEventListener('DOMContentLoaded', function () {
var eventSrc = new EventSource('event-source-2.php');
console.group('EventSource Created');
console.dir( eventSrc );
console.groupEnd();
eventSrc.addEventListener('open', function (event) {
console.time('Time Elapsed between open and message');
console.log(event.type);
});
eventSrc.addEventListener('message', function (event) {
console.timeEnd('Time Elapsed between open and message');
console.log(event);
console.dir( JSON.parse(event.data) );
});
}, false);
event-source-2.php
<?php
header("Content-Type: text/event-stream\n\n");
// despite not having the while(true){}
// this seems to repeat pushing messages to the client
echo 'data: ' . json_encode(
array(
0 => array(
'time' => time(),
'message' => 'Some kind of foo'
),
1 => array(
'time' => time(),
'message' => 'Some kind of quux'
)
)
) . "\n";
?>
Both examples can be found here: http://code.bocoup.com/event-source/event-source-1.html http://code.bocoup.com/event-source/event-source-2.html
They have only been tested in a Chromium nightly and definitely don’t work in FireFox. Be sure to have the javascript console open when running these in order to see the output.
EDIT
In the comments below, there is some interesting info about how this is actually implemented, most notably the comment left by obigid and my reply to them.
More Findings, May 27, 2010
In case you’re wondering what kind of HTTP request is being made, it is a GET request. Here are the passing tests:
https://gist.github.com/415836 https://gist.github.com/gists/415836/download