#!/usr/bin/perl -w use strict; use CGI; my @tickets = ( [ "GOOG", 533.37 ], [ "MSFT", 47.59 ], [ "IBM", 162.99 ], [ "AAPL", 114.12 ], [ "MSFT", 47.29 ], [ "GOOG", 533.95 ], [ "IBM", 163.78 ], [ "GOOG", 533.55 ], [ "AAPL", 113.67 ] ); my $ticketsLength = scalar ( @tickets ); my $lastId = 0; my $q = new CGI ; local $| = 1; print "Content-Type: text/event-stream\n"; print "Cache-Control: no-cache\n"; print "Connection: keep-alive\n\n"; while (1) { sendMessage($lastId, $tickets[$lastId][0], $tickets[$lastId][1]); $lastId++; die() if ($lastId >= $ticketsLength); # Check that lastId is not larger than the size of array - if it is larger close connection. sleep(1); } # Function to send data in format "ticket:price". sub sendMessage { my $id = shift(); my $ticket = shift(); my $price = shift(); print "id: $id\n"; print "data: $ticket:$price\n\n"; } #### Server Sent Events Perl Example - Stock Tickets

Server Sent Events Perl Example

This is simple Server Sent Events (SSE) example that updates stock prices when market moves. Data source is predefined array with prices and an update every second. This script is adapted from http://demo.howopensource.com/sse/

Tickets

IBM
161.57
AAPL
114.45
GOOG
532.94
MSFT
47.12

Simple Log Console

This is simple log console. It is useful for testing purposes and to understand better how SSE works. Event id and data are logged for each event.