Thursday, May 27th, 2010
Chrome supporting EventSource for server push, and richer Worker API
Rick Waldron has been delving into Chrome and Chromium to find some nice updates.
First, he uncovers new support for the EventSource API that allows for simple server push of DOM events as shown in this simple client and server pairing:
- 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);
< ?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";
[/php]
Then, he finds out that the Web Worker API now supports complex messages, so you can postMessage
more than Strings. Send over objects and Arrays with ease:
- // TEST ANOTHER THREAD SAFE OBJECT ARG
- var obj = new Object();
- obj.isArray = [ 1,2,3,4,5 ];
- obj.isString = 'Foo bar baz',
- obj.resultOf = (function () {
- return 'returned from self executing function';
- })();
- worker.postMessage(obj);
- // TEST STRING ARG
- worker.postMessage('Hello Worker Process');
- // TEST ARRAY ARG
- worker.postMessage([ 1, 2, 3, 4 ]);
- // TEST BOOLEAN ARG
- worker.postMessage(false);





Several WebWorker-related projects worth checking out (some mentioned on Ajaxian before):
1) Metaworker – mapreduce with workers – http://bit.ly/7oTuS5
2) Pmrpc – RPC/pubsub communication with workers and windows/iframes – http://bit.ly/JMtkm (I’m one of the developers)
3) jQuery Hive – creating and managing web workers across implementations – http://bit.ly/c5ihqm
4) Javascript Enumerable.Map() with WebWorkers – http://bit.ly/cY8M9P
I’ve made an example on which you can see Server-Sent Event in action using mentioned here Chrome 6, Safari 5 or Opera 9 – http://sapid.sourceforge.net/ssetest/
Just for a calcification on the comment within the events.php file that reads:
// despite not having the while(true){}
// this seems to repeat pushing messages to the client
You don’t need a while(true) block at all, because the user agent (browser) is going to ask for updates from that file about every 3 seconds unless you ask for different time, or the events.php returns a non 200 response from the server.
When you setup var eventSrc = new EventSource(‘events.php’); You told the browser that you want to check this file for updates. So the browser will request that file automatically.
—
The second thing that I would like to fix is the content-type of the event.php file. It should be header(“Content-Type: text/event-stream”); No NN at the end.
—
The third and final issue I see is that echo ‘data: ‘ . time() . “n”; should read echo ‘data: ‘ . time() . “\n\n”; Like headers, you one a single \n to end the line, and you use \n\n to end the section.