Rik's Ramblings

Monday, April 20, 2015

EventSource, for server side push to the browser

How did I not know about this spec before now!?


...in some scenarios data doesn't need to be sent from the client. You simply need updates from some server action. A few examples would be friends' status updates, stock tickers, news feeds, or other automated data push mechanisms ...


I tried it out on my own server, with a little perl test script and sure enough it works!


Server Test Code in Perl

#!/usr/bin/perl
print "content-type: text/event-stream\n\n";
$| = 1;  # Forces flush after every line

local $count = 10;

while (0 != $count){
   sleep(3);
   print "data: something".$count."\n\n";
   $count -= 1;
}





Browser Test Code in JavaScript

var eventurl = "http://server.dom/cgi-bin/server_side_events/test";
var foo = new window.EventSource(eventurl);
var bar = function(evt){ 
   console.log("BAR: "+JSON.stringify(evt.data)); 
};
foo.addEventListener("message", bar);





Try it now!